ArrayList: trimToSize() : ArrayList « java.util « Java by API






ArrayList: trimToSize()

  
/*
List contains 5 elements
List contains Integer(2): true
Integer(2) is at index 2
Get element at index 2: 99
Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 15
  at java.util.SubList.<init>(AbstractList.java:705)
  at java.util.RandomAccessSubList.<init>(AbstractList.java:861)
  at java.util.AbstractList.subList(AbstractList.java:570)
  at MainClass.main(MainClass.java:23)

*/
import java.util.ArrayList;

public class MainClass {
  public static void main(String[] args) {
    ArrayList myList = new ArrayList(5);
    for (int i = 0; i < 5; i++) {
      myList.add(new Integer(i));
    }
    System.out.println("List contains " + myList.size() + " elements");

    Integer int2 = new Integer(2);
    System.out.println("List contains Integer(2): " + myList.contains(int2));
    System.out.println("Integer(2) is at index " + myList.indexOf(int2));

    myList.set(2, new Integer(99));
    System.out.println("Get element at index 2: " + myList.get(2));

    myList.ensureCapacity(15);
    for (int i = 10; i < 15; i++) {
      myList.add(new Integer(i));
    }

    myList.subList(10, 15).clear();
    myList.trimToSize();


    System.out.println(myList);
  }
}

           
         
    
  








Related examples in the same category

1.new ArrayList < E > ()
2.new ArrayList(Collection c)
3.ArrayList: add(E o)
4.ArrayList: add(int index, E element)
5.ArrayList: addAll(Collection c)
6.ArrayList: addAll(int index, Collection c)
7.ArrayList: clear()
8.ArrayList: contains(Object elem)
9.ArrayList: equals(Object o)
10.ArrayList: ensureCapacity(int minCapacity)
11.ArrayList: get(int index)
12.ArrayList: indexOf(Object elem)
13.ArrayList: isEmpty()
14.ArrayList: iterator()
15.ArrayList: lastIndexOf(Object o)
16.ArrayList: listIterator()
17.ArrayList: remove(int index)
18.ArrayList: remove(Object o)
19.ArrayList: removeAll(Collection c)
20.ArrayList: retainAll(Collection c)
21.ArrayList: set(int index, T element)
22.ArrayList: size()
23.AbstractList: subList(int fromIndex, int toIndex)
24.ArrayList: toArray()
25.ArrayList: toArray(T[] a)
26.for each loop for ArrayList