Java Collections Framework:ArrayList-6.2

 

Java ArrayList trimToSize() Method example


trimToSize() method is used for memory optimization. It trims the capacity of ArrayList to the current list size. For e.g. An arraylist is having capacity of 15 but there are only 5 elements in it, calling trimToSize() method on this ArrayList would change the capacity from 15 to 5.

public void trimToSize()

Example

Here I have defined the ArrayList of capacity 50. After adding 10 elements I called trimToSize() method which would have reduced the capacity from 50 to 10 (current size of arraylist).

package beginnersbook.com;
import java.util.ArrayList;
public class TrimExample {
  public static void main(String args[]) {
    ArrayList<Integer> arraylist = new ArrayList<Integer>(50);
    arraylist.add(1);
    arraylist.add(2);
    arraylist.add(3);
    arraylist.add(4);
    arraylist.add(5);
    arraylist.add(6);
    arraylist.add(7);
    arraylist.add(1);
    arraylist.add(1);
    arraylist.add(1);
    arraylist.trimToSize();
    System.out.println(arraylist);
  }
}

Output:


[1, 2, 3, 4, 5, 6, 7, 1, 1, 1]

Java ArrayList set() Method example


If there is a need to update the list element based on the index then set method of ArrayList class can be used. The method set(int index, Element E) updates the element of specified index with the given element E.

public E set(int index, Element E)

Example:

In this example I have an ArrayList of Integer Type where I have added few elements and then I’m updating few of elements using set method of java.util.ArrayList class.

package beginnersbook.com;
import java.util.ArrayList;
public class SetExample {
  public static void main(String args[]) {
    ArrayList<Integer> arraylist = new ArrayList<Integer>();
    arraylist.add(1);
    arraylist.add(2);
    arraylist.add(3);
    arraylist.add(4);
    arraylist.add(5);
    arraylist.add(6);
    arraylist.add(7);
    System.out.println("ArrayList before update: "+arraylist);
    //Updating 1st element
    arraylist.set(0, 11);
    //Updating 2nd element
    arraylist.set(1, 22);
    //Updating 3rd element
    arraylist.set(2, 33);
    //Updating 4th element
    arraylist.set(3, 44);
    //Updating 5th element
    arraylist.set(4, 55);
    System.out.println("ArrayList after Update: "+arraylist);
  }
}

Output:



ArrayList before update: [1, 2, 3, 4, 5, 6, 7]
ArrayList after Update: [11, 22, 33, 44, 55, 6, 7]

Comments

Popular posts from this blog

Java OOPS:OOPS Concepts Overview

Java OOPS:Constructors in Java – A complete study!!

Java Basics:Data Types