What is List in Java?
List implements the Collection<E>, Iterable<E> Interfaces.
public interface List<E>
extends Collection<E>.
List in Java allows to store objects by storing them in each index. Other than Set List allows Duplication of elements.To store an element in List use the add() method and to get a value use get() method.
Some Classes implementing List Interface are ArrayList,LinkedList etc.
List throws these Exceptions:
UnsupportedOperationException
ClassCastException
NullPointerException
IllegalArgumentException
IndexOutOfBoundsException
Example:
package com.jobberindia;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> list = new ArrayList<String>();
list.add("Hello");
list.add("World");
list.add("Hello1");
list.add("World2");
System.out.println("Data stored in mainlist "+list);
System.out.println("Size of list before removing "+list.size());
ArrayList<String> subList = new ArrayList<String>(list.subList(1, 2));
System.out.println("Data stored in sublist "+subList);
System.out.println("Size of list before removing "+subList.size());
}
}
No comments:
Post a Comment