JAVA LIST INTERFACE
Some of the important points about Java List are:
· List Interface is the sub interface of Collection.
· It contains index-based methods to insert and delete elements.
· 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 Interface is implemented by ArrayList, LinkedList, Vector and Stack classes.
· List allows you to add duplicate elements.
· List allows you to have ‘null’ elements.
· List indexes start from 0, just like arrays.
1. List Interface declaration
· public interface List<E> extends Collection<E>
2. Java List Example
1. import java.util.*;
2. public class ListExample{
3. public static void main(String args[]){
4. List<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. System.out.println("An element at 2nd position: "+al.get(2));
10. for(String s:al){
11. System.out.println(s);
12. }
13. }
14. }
Output:
An element at 2nd position: Vijay
Amit
Sachin
Vijay
Kuma
Java List Methods
Some of the useful Java List methods are;
1. int size(): to get the number of elements in the list.
2. boolean isEmpty(): to check if list is empty or not.
3. boolean contains(Object o): Returns true if this list contains the specified element.
4. Iterator<E> iterator(): Returns an iterator over the elements in this list in proper sequence.
5. Object[] toArray(): Returns an array containing all of the elements in this list in proper sequence
6. boolean add(E e): Appends the specified element to the end of this list.
7. boolean remove(Object o): Removes the first occurrence of the specified element from this list.
8. boolean retainAll(Collection<?> c): Retains only the elements in this list that are contained in the specified collection.
9. void clear(): Removes all the elements from the list.
10. E get(int index): Returns the element at the specified position in the list.
11. E set(int index, E element): Replaces the element at the specified position in the list with the specified element.
12. ListIterator<E> listIterator(): Returns a list iterator over the elements in the list.
13. List<E> subList(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
Some of the default methods added to List in Java 8 are;
1. default void replaceAll(UnaryOperator<E> operator): Replaces each element of this list with the result of applying the operator to that element.
2. default void sort(Comparator<super E> c): Sorts this list according to the order induced by the specified Comparator.
3. default Spliterator<E> spliterator(): Creates a Spliterator over the elements in this list.