- Objects in a list
- Adding object to a list
- Adding user-inputted objects to a list
- Multiple constructor parameters
- Reading input in a specific format
- Filtered printing from the list
- Java List – Example Lists in Java
- Implementation Classes of the Java List Interface
- How to Implement a List in Java Using ArrayList
- How to Add Elements to the ArrayList
- How to Access Elements in the ArrayList
- How to Update Elements in the ArrayList
- How to Remove Elements in the ArrayList
- Summary
Objects in a list
The type parameter used in creating a list defines the type of the variables that are added to the list. For instance, ArrayList includes strings, ArrayList integers, and ArrayList floating point numbers
In the example below we first add strings to a list, after which the strings in the list are printed one by one.
ArrayListString> names = new ArrayList>(); // string can first be stored in a variable String name = "Betty Jennings"; // then add it to the list names.add(name); // strings can also be directly added to the list: names.add("Betty Snyder"); names.add("Frances Spence"); names.add("Kay McNulty"); names.add("Marlyn Wescoff"); names.add("Ruth Lichterman"); // several different repeat statements can be // used to go through the list elements // 1. while loop int index = 0; while (index names.size()) System.out.println(names.get(index)); index = index + 1; > // 2. for loop with index for (int i = 0; i names.size(); i++) System.out.println(names.get(i)); > System.out.println(); // 3. for each loop (no index) for (String name: names) System.out.println(name); >
Betty Jennings Betty Snyder Frances Spence Kay McNulty Marlyn Wescoff Ruth Lichterman
Betty Jennings Betty Snyder Frances Spence Kay McNulty Marlyn Wescoff Ruth Lichterman
Betty Jennings Betty Snyder Frances Spence Kay McNulty Marlyn Wescoff Ruth Lichterman
Adding object to a list
Strings are objects, so it should come as no surprise that other kinds of objects can also be found in lists. Next, let’s examine the cooperation of lists and objects in more detail.
Let’s assume we have access to the class defined below, describing a person.
public class Person private String name; private int age; private int weight; private int height; public Person(String name) this.name = name; this.age = 0; this.weight = 0; this.height = 0; > public String getName() return this.name; > public int getAge() return this.age; > public void growOlder() this.age = this.age + 1; > public void setHeight(int newHeight) this.height = newHeight; > public void setWeight(int newWeight) this.weight = newWeight; > public double bodyMassIndex() double heightDivByHundred = this.height / 100.0; return this.weight / (heightDivByHundred * heightDivByHundred); > @Override public String toString() return this.name + ", age " + this.age + " years"; > >
Handling objects in a list is not really different in any way from the previous experience we have with lists. The essential difference is only to define the type for the stored elements when you create the list.
In the example below we first create a list meant for storing Person type object, after which we add persons to it. Finally the person objects are printed one by one.
ArrayListPerson> persons = new ArrayList>(); // a person object can be created first Person john = new Person("John"); // and then added to the list persons.add(john); // person objects can also be created "in the same sentence" that they are added to the list persons.add(new Person("Matthew")); persons.add(new Person("Martin")); for (Person person: persons) System.out.println(person); >
John, age 0 years Matthew, age 0 years Martin, age 0 years
Adding user-inputted objects to a list
The structure we used earlier for reading inputs is still very useful.
Scanner scanner = new Scanner(System.in); ArrayListPerson> persons = new ArrayList>(); // Read the names of persons from the user while (true) System.out.print("Enter a name, empty will stop: "); String name = scanner.nextLine(); if (name.isEmpty()) break; > // Add to the list a new person // whose name is the previous user input persons.add(new Person(name)); > // Print the number of the entered persons, and their individual information System.out.println(); System.out.println("Persons in total: " + persons.size()); System.out.println("Persons: "); for (Person person: persons) System.out.println(person); >
Enter a name, empty will stop: Alan Kay Enter a name, empty will stop: Ivan Sutherland Enter a name, empty will stop: Kristen Nygaard
Persons in total: 3 Persons: Alan Kay, age 0 years Ivan Sutherland, age 0 years Kristen Nygaard, age 0 years
Multiple constructor parameters
If the constructor demands more than one parameter, you can query the user for more information. Let’s assume we have the following constructor for the class Person .
public class Person private String name; private int age; private int weight; private int height; public Person(String name, int age) this.name = name; this.age = age; this.weight = 0; this.height = 0; > // methods >
In this case, an object is created by calling the two-parameter constructor.
If we want to query the user for this kind of object, they must be asked for each parameter separately. In the example below, name and age parameters are asked separately from the user. Entering an empty name will end the reading part.
The persons are printed after they have been read.
Scanner scanner = new Scanner(System.in); ArrayListPerson> persons = new ArrayList>(); // Read person information from the user while (true) System.out.print("Enter name, empty will end: "); String name = scanner.nextLine(); if (name.isEmpty()) break; > System.out.print("Enter the age of the person " + name + ": "); int age = Integer.valueOf(scanner.nextLine()); // We add a new person to the list. // The person's name and age were decided by the user persons.add(new Person(name, age)); > // We'll print the number of the inputted persons, and the persons themselves System.out.println(); System.out.println("Total number of persons: " + persons.size()); System.out.println("Persons: "); for (Person person: persons) System.out.println(person); >
Enter name, empty will end: Grace Hopper Enter the age of the person Grace Hopper: 85 Enter name, empty will end:
Total number of persons: 1 Persons: Grace Hopper, age 85 years
Reading input in a specific format
In the example and exercise below, the required information was entered line by line. By no means is it impossible to ask for input in a specific format, e.g. separated by a comma.
If the name and age were separated by a comma, the program could work in the following manner.
Scanner scanner = new Scanner(System.in); ArrayListPerson> persons = new ArrayList>(); // Read person information from the user System.out.println("Enter the person details separated by a comma, e.g.: Randall,2"); while (true) System.out.print("Enter the details, empty will stop: "); String details = scanner.nextLine(); if (details.isEmpty()) break; > String[] parts = details.split(","); String name = parts[0]; int age = Integer.valueOf(parts[1]); persons.add(new Person(name, age)); > // Print the number of the entered persons, and the persons themselves System.out.println(); System.out.println("Total number of persons: " + persons.size()); System.out.println("Persons: "); for (Person person: persons) System.out.println(person); >
Enter the person details separated by a comma, e.g.: Randall,2 Enter the details, empty will stop: Leevi,2 Enter the details, empty will stop: Anton,2 Enter the details, empty will stop: Sylvi,0 Enter the details, empty will stop:
Total number of persons: 3 Persons: Leevi, age 2 years Anton, age 2 years Sylvi, age 0 years
Filtered printing from the list
You can also examine the objects on the list as you go through it. In the example below, we first ask the user for an age restriction, after which we print all the objects whose age is at least the number given by the user.
// Assume we have a 'persons' list // that consists of person objects System.out.print("What is the age limit? "); int ageLimit = Integer.valueOf(scanner.nextLine()); for (Person person: persons) if (person.getAge() >= ageLimit) System.out.println(person); > >
Remember to check your points from the ball on the bottom-right corner of the material!
Java List – Example Lists in Java
Ihechikara Vincent Abba
You can use the Java List interface to store objects/elements in an ordered collection. It extends the Collection interface.
The List interface provides us with various methods for inserting, accessing, and deleting elements in a collection.
In this article, you’ll learn how to extend and implement the List interface in Java, and how to interact with elements in a collection.
Implementation Classes of the Java List Interface
Here are the different implementation classes of the List interface in Java:
- AbstractList.
- AbstractSequentialList.
- ArrayList.
- AttributeList.
- CopyOnWriteArrayList.
- LinkedList.
- RoleList.
- RoleUnresolvedList.
- Stack.
- Vector.
The most commonly used implementation of the List interface are ArrayList and LinkedList .
Since both classes above implement the List interface, they make use of the same methods to add, access, update, and remove elements in a collection.
In this tutorial, we’ll have a look at how we can add, access, update, and remove elements in a collection using the ArrayList .
How to Implement a List in Java Using ArrayList
Unlike arrays in Java, which have a specified size, the ArrayList is more dynamic when it comes to storing elements. This means that you can add items as you please.
Here’s how you can create an ArrayList :
import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); > >
In the code above, we first imported the ArrayList class: import java.util.ArrayList; .
We then created a new ArrayList object called students : ArrayList students = new ArrayList(); .
Note that the data types of elements that would be stored in the ArrayList were specified in angle brackets: .
How to Add Elements to the ArrayList
You can use the add() method to add elements to the ArrayList .
import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); System.out.println(students); // [John, Jane, Doe] > >
In the code above, we passed the element to be added to the ArrayList as a parameter: students.add(«Doe») .
How to Access Elements in the ArrayList
To access elements in the ArrayList , you make use of the get() method. Here’s how:
import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); System.out.println(students.get(1)); // Jane > >
As can be seen above, we passed in the index of the element to be accessed as a parameter to the get() method: students.get(1) .
How to Update Elements in the ArrayList
To update the value of elements in the ArrayList , you make use of the set() method.
It takes two parameters: the index of the element to be updated, and the new value.
import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); students.set(2,"Jade"); System.out.println(students); // [John, Jane, Jade] > >
How to Remove Elements in the ArrayList
To remove elements in the ArrayList , you make use of the remove() method. We also use the index to specify which element to remove.
import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); students.remove(2); System.out.println(students); // [John, Jane] > >
You can use the clear() method to remove all the elements in the collection:
import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); students.clear(); System.out.println(students); // [] > >
Although the ArrayList and LinkedList classes both have the same methods as seen in the examples in this article, the LinkedList class has some additional methods like:
- addFirst() adds an element at the beginning of the list.
- addLast() adds an element at the end of the list.
- getFirst() returns the first element of the list.
- getLast() returns the last element of the list.
- removeFirst() removes the first element of the list.
- removeLast() removes the last element of the list.
Summary
In this article, we talked about the List interface in Java. You use it to store ordered collections of elements.
We had a look at some of the implementation classes of the List interface. The most commonly used are the ArrayList and LinkedList classes.
Using code examples, we saw how to add, access, update, and remove elements in a collection with the ArrayList .
Although both ArrayList and LinkedList have similar methods, we highlighted some of the additional methods that you can use with the LinkedList class.