ArrayList


ArrayList

ArrayList implements the List Interface where the elements can be dynamically added or removed from the list. The list size is increased dynamically if the elements added are more than the initial size.

Syntax:

ArrayList obj = new ArrayList ();

Various methods of arraylist are as follows:

  • add(Object): Used to add element at the end
  • add(int index,Object): Used to add element at a particular index
  • clone(): Used to return a shallow copy
  • clear(): Used to remove all elements
  • contains(): Used to check whether an element is present or not
  • get(int index): Used to return element at specified postion
  • remove(Object): Used to remove an element
  • removeAll(): Used to remove all the elements
  • size(): Used to return number of elements
  • subList(int from,int to): Used to return a part of the arraylist as specified

Example No.1:

Com.knowledge2life import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> Web = new ArrayList<String>(); Web.add("Knowledge2life1"); Web.add("Knowledge2life2"); Web.add("Knowledge2life3"); Web.add("Knowledge2life4"); System.out.println(Web); } }

OUTPUT:

[Knowledge2life1, Knowledge2life2, Knowledge2life3, Knowledge2life4]

Example No.2:

Com.knowledge2life import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Knowledge2life1"); cars.add("Knowledge2life2"); cars.add("Knowledge2life3"); cars.add("Knowledge2life4"); for (int i = 0; i < cars.size(); i++) { System.out.println(cars.get(i)); } } }

OUTPUT:

Knowledge2life1
Knowledge2life2
Knowledge2life3
Knowledge2life4