Collection OperationsThe operations inherited from Collection all do about what you'd expect them to do, assuming you're already familiar with them. If you're not familiar with them from Collection, now would be a good time to read The Collection Interface section. The remove operation always removes the first occurrence of the specified element from the list. The add and addAll operations always append the new element(s) to the end of the list. Thus, the following idiom concatenates one list to another. Show
Here's a nondestructive form of this idiom, which produces a third List consisting of the second list appended to the first. List list3 = new ArrayList(list1);
list3.addAll(list2);
Note that the idiom, in its nondestructive form, takes advantage of ArrayList's standard conversion constructor. And here's an example (JDK 8 and later) that aggregates some names into a List: List list = people.stream()
.map(Person::getName)
.collect(Collectors.toList());
Like the Set interface, List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes. Two List objects are equal if they contain the same elements in the same order. List Interface in Java with ExamplesThe List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. The List interface is found in java.util package and inherits the Collection interface. It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5. Declaration: The List interface is declared as: public interface List<E> extends Collection<E>;Let us elaborate on creating objects or instances in a List class. Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List. Just like several other user-defined ‘interfaces’ implemented by user-defined ‘classes’, List is an ‘interface’, implemented by the ArrayList class, pre-defined in the java.util package. Syntax: This type of safelist can be defined as: List<Obj> list = new ArrayList<Obj> ();
Example: Java
Output
[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]
Now let us perform various operations using List Interface to have a better understanding of the same. We will be discussing the following operations listed below and later on implementing via clean java codes. Operations in a List interfaceSince List is an interface, it can be used only with a class that implements this interface. Now, let’s see how to perform a few frequently used operations on the List.
Now let us discuss the operations individually and implement the same in the code to grasp a better grip over it. Operation 1: Adding elements to List class using add() method In order to add an element to the list, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. Parameters: It takes 2 parameters, namely:
Example: Java
Output
[Geeks, For, Geeks]
Operation 2: Updating elements After adding the elements, if we wish to change the element, it can be done using the set() method. Since List is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index. Example: Java
Output
Initial ArrayList [Geeks, Geeks, Geeks]
Updated ArrayList [Geeks, For, Geeks]
Operation 3: Removing Elements In order to remove an element from a list, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are: Parameters:
Example: Java
Output
Initial ArrayList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]
Iterating over ListTill now we are having a very small input size and we are doing operations manually for every entity. Now let us discuss various ways by which we can iterate over the list to get them working for a larger sample set. Methods: There are multiple ways to iterate through the List. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop. Example: Java
Output
Geeks For Geeks
Geeks For Geeks
Methods of the List InterfaceSince the main concept behind the different types of the lists is the same, the list interface contains the following methods:
Java List vs SetBoth the List interface and the Set interface inherits the Collection interface. However, there exists some differences between them.
Classes Association with a List InterfaceNow let us discuss the classes that implement the List Interface for which first do refer to the pictorial representation below to have a better understanding of the List interface. It is as follows: AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the List interface. A separate functionality is implemented in each of the mentioned classes. They are as follows:
We will proceed in this manner.
Let us discuss them sequentially and implement the same to figure out the working of the classes with the List interface. Class 1: ArrayListAn ArrayList class which is implemented in the collection framework provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. Let’s see how to create a list object using this class. Example: Java
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Class 2: VectorVector is a class that is implemented in the collection framework implements a growable array of objects. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. Vectors basically fall in legacy classes but now it is fully compatible with collections. Let’s see how to create a list object using this class. Example: Java
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Class 3: StackStack is a class that is implemented in the collection framework and extends the vector class models and implements the Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. Let’s see how to create a list object using this class. Example: Java
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Class 4: LinkedListLinkedList is a class that is implemented in the collection framework which inherently implements the linked list data structure. It is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. Let’s see how to create a list object using this class. Example: Java
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Article Tags :
Java
Java - util package Java-Collections java-list Practice Tags :
Java Java-Collections ArrayList in JavaArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. Illustration: Example: The following implementation demonstrates how to create and use an ArrayList. Java
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item:
Important Features:
Let’s understand the Java ArrayList in depth. Look at the below image: In the above illustration, AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are:
Constructors in the ArrayListIn order to create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists of various constructors which allow the possible creation of the array list. The following are the constructors available in this class: 1. ArrayList(): This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr, then, it can be created as:
2. ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present in the collection c, then, it can be created as:
3. ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:
Methods in Java ArrayList
Let’s see how to perform some basics operations on the ArrayList as listed which we are going to discuss further alongside implementing every operation.
Operation 1: Adding Elements In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:
Example: Java
Output:
[Geeks, For, Geeks]
Operation 2: Changing Elements After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index. Example Java
Output:
Initial ArrayList [Geeks, Geeks, Geeks]
Updated ArrayList [Geeks, For, Geeks]
Operation 3: Removing Elements In order to remove an element from an ArrayList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:
Example Java
Output:
Initial ArrayList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]
Operation 4: Iterating the ArrayList There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for loop. Example Java
Output:
Geeks For Geeks
Geeks For Geeks
Must Read: Array vs ArrayList in Java
Article Tags :
Java Technical Scripter
Java - util package Java-ArrayList Java-Collections java-list Practice Tags :
Java Java-Collections Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion. Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet). What is Collection in JavaA Collection represents a single unit of objects, i.e., a group. What is a framework in Java
What is Collection frameworkThe Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:
Do You Know?
Hierarchy of Collection FrameworkLet us see the hierarchy of Collection framework. The java.util package contains all the classes and interfaces for the Collection framework. Methods of Collection interfaceThere are many methods declared in the Collection interface. They are as follows:
Iterator interface
Methods of Iterator interfaceThere are only three methods in the Iterator interface. They are:
|