ArrayList


ArrayList is resizable implementation of List interface.Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

import java.util.*;
public class ArrayListExample {
           
            @SuppressWarnings("unchecked")
            public static void main(String[] args) {
                        List rajniList = new ArrayList();
                        //adding element in ArrayList
                        rajniList.add ("item1");
                        rajniList.add (2);
                        rajniList.add (new Integer(3));
                        rajniList.add ("item4");
                        rajniList.add ("item4");
                        rajniList.add (null);
                        System.out.println (rajniList); //o/p: [item1, 2, 3, item4, item4, null]
                        int  sizeOfRajniList = rajniList.size();             //checking size of ArrayList
                        System.out.println (sizeOfRajniList);             //o/p: 6
                        int itemIndex = rajniList.indexOf (2);  //Finding index of an item
                        System.out.println (itemIndex);                //o/p :1
                        //Retrieving Items from arrayList
                        fo r (Object itemList : rajniList){
                                    System.out.print(itemList+" ");   //o/p: item1 2 3 item4 item4 null
                        }
                        //Removing an item from ArrayList:
                        rajniList.remove(0);     //Remove first element from ArrayList
                        rajniList.remove(2);     //Remove first occurance of element '2'
                        System.out.println (rajniList);             //o/p: [2, 3, item4, null]
            }
}



import java.util.Arrays;
import java.util.List;

public class ArraysToList {

            @SuppressWarnings("unchecked")
            public static void main (String[] args) {
                        String stringArray[] = {"John","Milli","Albert","Matt"};
                        List sList = Arrays.asList (stringArray);
                        System.out.println ("Size "+ sList.size());
                        System.out.println ("Element at index 2 :" + sList.get (2));
                        //When you update one of them,the other get updated automatically.
                        sList.set (3,"Sam");
                        stringArray[1] = "Macc";
                        for(String s : stringArray){
                                    System.out.print (s + " ") ;
                        }
                        System.out.println ( "\n sList[1] "+sList.get(1));
            }
}

Output of the above:
Size 4
Element at index 2 :Albert
John Macc Albert Sam
sList[1] Macc


import java.util.ArrayList;
import java.util.List;

public class ListsToArray {

            public static void main (String[] args) {
                        List<Integer>  integerList  =  new ArrayList <Integer>();
                        for (int x=0; x<3; x++)
                                    integerList.add (x);
                        //creating an Object array
                        Object[]  objectArray = integerList.toArray();
                        Integer[]  integerArray = new Integer[3];
                        //creating an Integer array
                        integerArray  =  integerList.toArray (integerArray);
            }
}

More methods related to : ArrayList, List and Arrays.


The sort algorithm reorders a List so that its elements are in ascending order according to an ordering relationship.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class SortingArrayList {
            @SuppressWarnings ("unchecked")
            public static void main (String[] args) {
                        ArrayList  arrayList = new ArrayList();
                        arrayList.add ("A");
                        arrayList.add ("C");
                        arrayList.add ("D");
                        arrayList.add ("E");
                        arrayList.add ("B");
                       
                        /*
                          To get comparator that imposes reverse order on a Collection use
                          static Comparator reverseOrder() method of Collections class
                        */
                        Comparator  comparator  =  Collections.reverseOrder();
                        System.out.println ("Before sorting ArrayList in descending order : "
                                                                                   +  arrayList);
                        Collections.sort (arrayList);
                        System.out.println ("Sorting without comparator : " + arrayList);
                        /*
                          To sort an ArrayList using comparator use,
                          static void sort(List list, Comparator c) method of Collections class.
                        */
                        Collections.sort (arrayList, comparator);
                        System.out.println ("After sorting ArrayList in descending order : "
                                                                                  +  arrayList);
            }
}
Output of the above:
Before sorting ArrayList in descending order : [A, C, D, E, B]
Sorting without comparator : [A, B, C, D, E]
After sorting ArrayList in descending order : [E, D, C, B, A]


Merging of two ArrayLists can be done using  addAll(Collection c)  method and then can be sorted using Collections.sort(arrayList).

import java.util.*;
 public class MergingArraylistInSortedList {
            public static void main (String[] args) {
              List <Integer>  rajniList1 =  new  ArrayList <Integer>();
              List <Integer>  rajniList2 =  new  ArrayList <Integer>();
              rajniList1. add(5);
              rajniList1. add(2);
              rajniList2. add(7);
              rajniList2. add(1);
              List <Integer>  newRajniList  =  new  ArrayLis t<Integer>(rajniList1);
              //Merging rajniList2 into newRajniList
              newRajniList.addAll (rajniList2);
              System.out.println ("Mergerd list " + newRajniList);
              //sorting the merged ArrayList
              Collections.sort (newRajniList);
              System.out.println ("sorted List " + newRajniList);
    }
 }
Output of the above:

Mergerd list [5, 2, 7, 1]
sorted List [1, 2, 5, 7]

See also SortedArrayList.


Important points which must be kept while searching an element in Array/ArrayList(or any Collections class).
  • For searching an element binarySearch() method is used.
  • The collection/Array being searched must be sorted else will give wrong result.
  • If the collection/Array which is being searched using Comparator,it must be searched using the same Comparator,which is passed as the second argument to the binarySearch() method.
  • Successful searches returns the int index(including 0) of the element, if search is unsuccessful  it returns negative int index which represents insertion point to keep collection/Array sorted.The actual insertion point is (-(insertion point)-1).

import java.util.*;
 public class SearchingArrayList {
    public static void main (String[] args) {
                        List<String>  rajniList = new  ArrayList<String>();
                        rajniList.add ("one");
                        rajniList.add ("two");
                        rajniList.add ("three");
                        rajniList.add ("four");
                        Collections.sort (rajniList);//Before searching list must be sorted
                        for(String rs: rajniList)
                                    System.out.print (rs + " ");
                        System.out.println ("\nindex of one :"
                                                + Collections.binarySearch (rajniList,"one"));
                        System.out.println ("Now using reverse sort :");
                        RajniReverseSort   rSort  =  new  RajniReverseSort();
                        Collections.sort (rajniList,rSort);
                        for(String rs : rajniList)
                                    System.out.print (rs + " ");
                        //Result will be unpredictable as Comparator not used
                        System.out.println ("\nindex of two: "
                                                +  Collections.binarySearch (rajniList, "two"));
                        System.out.println ("index of two: " +
                                                Collections.binarySearch (rajniList, "two", rSort));
            }
            static class RajniReverseSort implements Comparator<String>{
                        @Override
                        public int compare (String  a, String  b) {
                                    return b.compareTo(a);
                        }
            }
 }
Output:

four one three two

index of one :1
Now using reverse sort :
two three one four
index of two: -5
index of two: 0

You must want to read about Vector , Set Interface , Map Interface

7 comments:

  1. This is really helpful. Thanks a bunch!!

    ReplyDelete
  2. Please submit code for merging arraylist so that the resultant arraylist is in sorted order. Thanks!

    ReplyDelete
  3. Good post you have indeed covered topic in good details with sample code and easy explanaiton.
    you can also see 10 Arraylist Java Example for more examples of arraylist.

    ReplyDelete
  4. Thanks for the sample code for merging and sorting. Appreciate it!!

    ReplyDelete
  5. how genius u r............

    ReplyDelete
    Replies
    1. I m really happy if its helped u..

      Delete
  6. THANKS A LOT...........

    ReplyDelete