List in Java

List Interface in Java with Examples

The List interface 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.

List<Integer> l1 = new ArrayList<Integer>(); 

Performing various operations using List Interface and ArrayList class

Adding Elements
  • add(Object): This method is used to add an element at the end of the List.
  • add(int index, Object): This method is used to add an element at a specific index in the List.
Changing 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.

Removing Elements
  • remove(Object): This method is used to simply remove an object from the List. If there are multiple such objects, then the first occurrence of the object is removed.
  • remove(int index): Since a List is indexed, this method takes an integer value which simply removes the element present at that specific index in the List. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.
Iterating the List

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 loop.

Leave a Reply