List interface

List interface

List interface is an ordered collection allowing us to store and access elements sequentially. It extends the collection interface. Objects cannot be created as list is an interface. Java.util.List package is imported to use the list interface.

The classes that implement list interface are as follows:

  • ArrayList
  • LinkedList
  • Vector
  • Stack


List<String> l1=new ArrayList<>(); List<String> l2=new LinkedList<>();

Here are some key points about the Java list interface:

  • You can insert or access the elements by their position in a list by using the zero-based index.
  • A list might have duplicate values.
  • Along with the methods that the Collection class defines, the list also has some other methods of its own.
  • Several list methods give the UnsupportedOperationException if it is impossible to modify the collection and the ClassCastException if an object is not compatible with the other.

List interface methods in java:

  • Here are some methods commonly used in the List interface:

    • add() – It adds an element to list
    • addAll() – It adds all elements of a list to another
    • get() – It randomly accesses the list elements
    • iterator() – It returns iterator object for sequentially accessing list elements
    • set() – It changes list elements
    • remove() – It removes a list element
    • removeAll() – It removes all the list elements
    • clear() – It efficiently removes all the list elements
    • size() – It returns the list’s length
    • toArray() – It converts a list to an array
    • contains() – rIt returns true if the list has some specified element


    Com.knowledge2life import java.util.*; public class Main { public static void main(String[] args) { List<Integer> l1 = new ArrayList<Integer>(); l1.add(0, 1); l1.add(1, 2); System.out.println(l1); List<Integer> l2 = new ArrayList<Integer>(); l2.add(1); l2.add(2); l2.add(3); l1.addAll(1, l2); System.out.println(l1); l1.remove(1); System.out.println(l1); System.out.println(l1.get(3)); l1.set(0, 5); System.out.println(l1); } }


    [1, 2]
    [1, 1, 2, 3, 2]
    [1, 2, 3, 2]
    [5, 2, 3, 2]