Java Topics

ArrayList

✓ ArrayList implements List, Collection, Cloneable, Serializable, Iterable and randomaccess interfaces.

✓ ArrayList was introduced in JDK 1.2 version.

✓ The underlying data structure for the ArrayList is resizable array.

✓ The initial capacity of ArrayList is 10.


ex: 

import java.util.*;

public class ArrayList {

public static void main(String[] args) {

ArrayList<String> a = new ArrayList<String>();

a.add("steve");

a.add("tom");

a.add("cat");

a.add("jerry");

//display elements

System.out.print(a+" "); //output : steve tom cat jerry

//Add vijay at 3rd position

a.add(2,"vijay"); 

System.out.print(a+" ");// output  : steve tom vijay cat jerry

//To update the value at particular index

a.set(0,"rosy");

System.out.print(a+" ");// output  : rosy tom vijay cat jerry

//To remove the element at particular index

a.remove(1);

System.out.print(a+" ");// output  : rosy vijay cat jerry

//using for each loop we can display the results

for(String s : a) {

System.out.println(s);

}

//To display the size of ArrayList

System.out.print(a.size());//output  : 4

//To sort the elements in Alphabetical order

Collections.sort(a);

for(String s : a) {

System.out.print(s+" ");// output  : cat jerry rosy vijay

}

   }

}

Note:

✓With in the collections no primitive values are allowed.

✓ If you try to add primitive values then that will be converted into its corresponding wrapper class object and address of object will be stored within the given collection.

✓Collection class have some inbuilt methods  like sort() and search(). By using this class we can sort elements present in ArrayList.