
ArrayList Class in Java
ArrayList Class in Java
Introduction:
- ArrayList is implemented from List Interface.
- It allows to store different types of elements when compare to array.
- It also allows increase and decrease the elements dynamically.
- It store the elements based on index and print the same order we given.
- It allows user to store duplication of elements.
Creating ArrayList:
ArrayList object=new ArrayList(); // without generics
ArrayList<T> object=new ArrayList<T>(); // with generics |
Example:
ArrayList al=new ArrayList(); ArrayList<Long> al=new ArrayList<Long>(); |
Methods:
boolean add(E)
E-Element
Add the element E in end of the list.
void add(int,E)
int – index of the element , E – element
Add the element in the given index
boolean contains(Object)
It returns true, particular Element is available in the List
It returns false, Element not available
int size()
It returns the no.of elements in the list.
boolean is Empty()
It returns true, List is Empty. Otherwise list is not empty.
E remove(int)
int – index of the element
It will remove the element for the particular index from the ArrayList.
E get(int)
int – index of the element
It returns the Element for the particular index.
void set(int, E)
Int – index of the element , E – element
It used to store the element in particular index
Iterator iterator()
It returns the all the elements in the ArrayList to Iterator Interface
boolean addAll(Collection c)
Add The Collection into ArrayList at the end
List subList(int,int)
int – start index , int –end index
It returns the List based on sublist of start and end index.
Example:
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListExample { public static void main(String[] args) { ArrayList al=new ArrayList(); al.add(0, 2); al.add(1, 2.3f); al.add(2, "hello"); al.add(3, 12345678); al.add(4, true); System.out.println("Elements at Clone:"+al.clone()); System.out.println("Elements at index :"+al.get(2)); System.out.println("Size Of Elements:"+al.size()); System.out.println("Elements contains:"+al.contains(2.3f)); Iterator i=al.iterator(); while(i.hasNext()) { System.out.println("Al Elements:"+i.next()); } al.add('c'); System.out.println("Elements after add:"+al.clone()); al.set(4, false); System.out.println("Elements after set:"+al.clone()); al.remove(3); System.out.println("Elements after remove:"+al.clone()); List sl=al.subList(1, 3); System.out.println("Elements after sublist:"+sl); } } |
Output:
Elements at Clone:[2, 2.3, hello, 12345678, true] Elements at index :hello Size Of Elements:5 Elements contains:true Al Elements:2 Al Elements:2.3 Al Elements:hello Al Elements:12345678 Al Elements:true Elements after add:[2, 2.3, hello, 12345678, true, c] Elements after set:[2, 2.3, hello, 12345678, false, c] Elements after remove:[2, 2.3, hello, false, c] Elements after sublist:[2.3, hello] |