ARRAYLIST IMPORTANT METHODS

ArrayList Important methods


trimToSize():

    It is one of the important method in ArrayList class.

  • By using trimToSize() we can remove unwanted dimension space from ArrayList.

Syntax:

    public void trimToSize()

Example 1:

 
						
              package com.sdj.pack2;
              public class TrimToSize
              {
                 public static void main(String[] args)
                 {
                    ArrayList l1=new ArrayList(2);
                    l1.add("add");
                    l1.add("xyz");
                    l1.add("pqr");
                    l1.trimToSize();
                    l1.add("123");
                    System.out.println(l1);
                 }
                 
                 /* In the above program the ArrayList initial size is 2. */
                 /* But if we add more than 2 elements to List, Then list */
                 /* size will increase double the current size .*/
                 /* In the above after 2 dimensional we can add(“pqr”). */
                 /* So the initial size increased to double size  i.e  */ 
                 /* 4 . but we are using only 3 elements ,here we can avoid */
                 /* that unused space by using trimToSize(). */
            } 
                

Output:

[add, xyz, pqr, 123]

ensureCapacity(int size):

    By using ensureCapacity(int size) We can update dimension of the ArrayList dynamically.

Syntax:

    public void ensureCapacity(int minCapacity)

Example 2:

 
						
              package com.sdj.pack2;
              public class TrimToSize
              {
                 public static void main(String[] args)
                 {
                    ArrayList l1=new ArrayList(2);
                    l1.add("add");
                    l1.add("xyz");
                    l1.add("pqr");
                    l1.trimToSize();
                    l1.add("123");
                    l1.ensureCapacity(100);
                    /* here we are updating List dimension  to 100   dynamically*/
                    System.out.println(l1);
                 }
              }                

Output:

[add, xyz, pqr, 123]

remove( int index):

    It will remove the specified element based on index from List object and returns the same element to user.

Syntax:

    public Object remove(int index)

public Object remove (Object):

    This method is used for removing the objects from List object based on the content.

removeAll(collection):

    It will removes all elements from current/this collection object which are common in the specified/parameter collection object

Example 3:

 
						
              package com.sdj.pack2;
              public class TrimToSize
              {
                 public static void main(String[] args)
                 {
                    ArrayList list1=new ArrayList(2);
                    list1.add(10);
                    list1.add(20);
                    list1.add(30);
                    list1.add(50);
                    ArrayList list1=new ArrayList(2);
                    list2.add(40);
                    list2.add(20);
                    list2.add(50);
                    System.out.println(“List1 before remove All:”+list1);
                    System.out.println(“List2 before remove All:”+list2);
                    list1.removeAll(list2);
                    System.out.println(“List1 after remove All:”+list1);
                    System.out.println(“List2 after  remove All:”+list2);
                 }
              }                

Output:

List1 before remove All: [10, 20, 30,50] List2 before remove All: [20, 40,50] List1 after remove All: [10,30] List2 after remove All: [20,40,50]

Explanation:

    Here the element “20” and “50” are common in both list1 and list2 ,though these elements are removed from list1 they are not removed from list2 object.

    Note

    Current object means by using which collection object we are calling removeAll(), that acts as current object or this object.

retainAll:

    It will maintain common elements and delete uncommon elements from current collection object by comparing with parameter or input collection object.

    Note

      Current object means by using which collection object we are calling retainAll(), that acts as current object or this object.

Syntax:

    boolean retainAll(Collection parameterCollection);

Example 4:

 
						
               package com.sdj.pack1;
               
               import java.util.ArrayList;
               
               public class RetainAll
               {
                  public static void main(String[] args)
                  {
                     ArrayList list1=new ArrayList(2);
                     list1.add(10);
                     list1.add(20);
                     list1.add(30);
                     list1.add(50);
                     ArrayList list1=new ArrayList(2);
                     list2.add(40);
                     list2.add(20);
                     list2.add(50);
                     System.out.println(“List1 before retain All:”+list1);
                     System.out.println(“List2 before retain All:”+list2);
                     list1.retainAll(list2);
                     System.out.println(“List1 after retain All:”+list1);
                     System.out.println(“List2 after  retain All:”+list2);
                  }
               }                  

Output:

List1 before retain All: [10, 20, 30,50] List2 before retain All: [20, 40,50] List1 after retain All: [20,50] List2 after retain All: [20,40,50]

Explanation:

    Here the element “20” and “50” are common in both list1 and list2 ,Since these elements are PRESENT in list1 and remaining uncommon elements i.e 10,30 are deleted , But any elements will not be removed from list2 object.

removeRange(int fromIndex,int toIndex):

    If we want to remove the elements from collection object within a specified range, we should use removeRange().If input index is out of collection index range then we will get IndexOutOfException.

Syntax:

    protected void removeRange(intfromIndex,int toIndex )

    removeRange method accesslevel is protected. So it’s default scope is within the package i.e java.util only. So if we wan to use this method in our class then we should extends ArrayList class to our class. Then perform what all the operations you want to perform with our class only.But we need to create object to Array List class. Why because protected + inherited member acts as private and specific to sub class.

Example 5:

 
						
               package com.sdj.pack1;
               public class MyArrayList  extends ArrayList
               {
                  public static void main(String[] args)
                  {
                     MyArrayList  outList= new MyArrayList ();
                     outList.add("java");
                     outList.add("oracle");
                     outList.add("j2ee");
                     outList.add("SQL");
                     outList.add("SDJ");
                     outList.add("Spring");
                     System.out.println(outList);
                     outList.removeRange(1,3);
                     System.out.println(outList);
                  }
               }                

Output:

IndExample 0 1 2 3 4 5 List elements before callRemoveRange: [java, oracle, j2ee, SQL, SDJ, Spring] IndExample 0 1 2 3 List elements after call RemoveRange(1,3): [java, SQL, SDJ, Spring]

Explanation:

    removeRange will takes two inputs i.e starting index and ending index, Here Starting index is taken as include operation and ending index will be takesn as exclude operation.

    From above example we are calling removeRange(1,3) means we need to remove elements for list which are present in index 1 and 2 only but should not delete from index 3 position value.

How To Sort The List:

    if we want to sort the elements in List Object, Then we should go sort(List list) it is present in java.util.Collection class.But we don’t have any special class for sorting the elements in List interface.

How to convert List to Array (or) Viceversa:

    If we want to convert from List to Arrays . For this List interface is provided one method i.e. toArray().

Syntax:

    1. public Object[] toArray();

    2. public specifiedType[] toArray(Object specificType[]);

toArray():

    It will convert List object to Object type array type and dump all List elements into that corresponding Array object.

    Note

      By default toArray() will gives output as Object type of array only. i.e. Object obj[].

     If we want to convert List object to our own specified array type then we should go for another type of toArray() method . i.e. toArray(Object specifiType[]). Here specify the Type i.e., which type of arrayType you are expecting as output from List object.

    Examples:

    • Object listArray[] = list.toArray();
    • String listArray[] = list.toArray(); // its not possible. Why because we are try to assigning Object array to String array type
    • String listArray[] = list.toArray(new String[list.size()]);// it’s works fine.
    • Int listArray[] = list.toArray(new int[list.size()]); … etc.

Example 5:

 
                        
               package com.sdj.pack1;
               public class ToAray
               {
                  public static void main(String[] args)
                  {
                     List l1=new ArrayList();
                     l1.add("abc");
                     l1.add(77);
                     l1.add("cmhc");
                     l1.add(35);
                     l1.add(56);
                     l1.add(21);
                     System.out.println(l1);
                     Object listArray[]=l1.toArray();
                     System.out.println(listArray);
                     System.out.println(l1);
                  }
               }                    

Output:

Rsult of List object: [abc, 77, cmhc, 35, 56, 21] Result of toArray(): [Ljava.lang.Object;@10b62c9

Explanation:

    In Arrays toString() can’t override. Due to this we are getting output like [Ljava.lang.Object;@10b62c9 i.e ClassName@HexaMemorylocation.

Example 6:

 
                        
                     package com.sdj.pack1;
                     public class ToAray
                     {
                        public static void main(String[] args)
                        {
                           ArrayList l1=new ArrayList();
                           l1.add("abc");
                           l1.add("pqr");
                           l1.add("cmhc");
                           System.out.println(l1);
                           Object obj[]=l1.toArray();
                           Object o1=obj[0];
                           /* System.out.println(o1.length()); */
                           /* Here compilation fails why because  the method “length()” */
                           /* is undefined for the Object. So comment above line. That */
                           /* method is part of Array class. i.e By using super class ref */
                           /* var we can’t access sub class specific members. */
                           for (Object elemt : o1)
                           {
                              System.out.println(elemt);
                           }
                        }
                     }                

Output:

Result of list : [abc, pqr, cmhc] Result of array through forloop: abc Pqr cmhc