list interface in java collection


  1. It is the child interface of the collection.

  2. If we want to represent a group of individual objects as a single entity where duplicates are allowed and insertion order is preserved then we should go for the list.

  3. We can differentiate duplicates by using the index.


We preserve insertion order by using index, Hence Index plays a very important role in list interface.

Since List is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following List implementations in the Java Collections API:

list interface

  • java.util.ArrayList

  • java.util.LinkedList

  • java.util.Vector

  • java.util.Stack


Operations on list interface


In addition to the operations inherited from Collection, the List interface includes operations for the following:

  1. Positional access — manipulates elements based on their numerical position in the list. This includes methods such as get, set, add, addAll, and remove.

    • void add(int index, Object O): This method adds given element at specified index.

    • boolean addAll(int index, Collection c): This method adds all elements from the specified collection to list. The first element gets inserted at given index. If there is already an element at that position, that element and other subsequent elements(if any) are shifted to the right by increasing their index.

    • Object remove(int index): This method removes an element from the specified index. It shifts subsequent elements(if any) to left and decreases their indexes by 1.

    • Object get(int index): This method returns the element at the specified index.

    • Object set(int index, Object new): This method replaces element at given index with the new element. This function returns the element which was just replaced by the new element.



  2. Search — searches for a specified object in the list and returns its numerical position. Search methods include indexOf and lastIndexOf.

    • int indexOf(Object o): This method returns the first occurrence of given element or -1 if the element is not present in the list.

    • int lastIndexOf(Object o): This method returns the last occurrence of given element or -1 if the element is not present in the list.



  3. Iteration — extends Iterator semantics to take advantage of the list's sequential nature. The listIterator methods provide this behavior. we will learn more about this in our cursor topic.

  4. Range-view — The sublist method performs arbitrary range operations on the list.

    • List subList(int fromIndex,int toIndex):This method returns List view of specified List between fromIndex(inclusive) and toIndex(exclusive).




 

Note: The set and remove operations return the old value that is being overwritten or removed. search operations (indexOf and lastIndexOf) return the first or last index of the specified element in the list.

Comments