List Interface in Java
List Interface in Java
The List interface is used by one of the most popular classes in Java
collections which is ArrayList. It is also implemented by the LinkedList class.
It is also implemented by the Vector class and it is also used by the Stack
class which is inherited from the Vector class. These are the 4 main classes
in Java collections that implement the List interface.
Now, List interface inherits Collection interface, so it has all the methods
available in the Collection interface and along with them it has some
additional methods specific to List Interface only.
Example of a List:
Java
// Adds 1 at 0 index
l1.add(0, 1);
// Adds 2 at 1 index
l1.add(1, 2);
System.out.println(l1);
l2.add(1);
l2.add(2);
l2.add(3);
Output:
[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]
Method Description
This method replaces element at given index with new element. This
set(int index, E function returns the element which was just replaced by new
element) element. Since it is a generic function, so "E" here is denotes the
type of element in the List.
Advantages: