Modifying Capacity – Collections, Part I: ArrayList

Modifying Capacity

The following two methods can be used to modify the capacity of a list. There is no method that returns the current capacity of an ArrayList<E>.

void trimToSize()

Trims the capacity of this list to its current size.

Click here to view code image

void ensureCapacity(int minCapacity)                
From
 List<E>
interface
.

Ensures that the capacity of this list is large enough to hold at least the number of elements specified by the minimum capacity.

All the code snippets in this section can be found in Example 12.1, p. 663. The method printListWithIndex() at (16) in Example 12.1 prints the elements prefixed with their index in the list, making it easier to see how the list changes structurally:

Click here to view code image

[0:level, 1:Ada, 2:Java, 3:kayak, 4:Bob, 5:Rotator, 6:Bob]

We have seen that the add(E) method appends an element to the end of the list. The following code adds the strings from an array of String to an ArrayList of String. The output from Example 12.1 at (2) shows how the elements are added at the end of the list.

Click here to view code image

System.out.println(“\n(2) Add elements to list:”);
for (String str : wordArray) {
  strList.add(str);
  printListWithIndex(strList);
}

We can insert a new element at a specific index using the overloaded method add(int, E). The output from the following code shows how inserting an element at index 2 shifted the elements structurally in the list.

Click here to view code image

    
                        // [0:level, 1:Ada, 2:kayak, 3:Bob, 4:Rotator, 5:Bob]
strList.add(2, “Java”);      // Insert an element at index 2 in the list.
printListWithIndex(strList); // [0:level, 1:Ada, 2:Java, 3:kayak, 4:Bob,
                             //  5:Rotator, 6:Bob]

Note that an index value equal to 0 or the size of the list is always allowed for the method add(int, E).

Click here to view code image

List<String> list1 = new ArrayList<>();   // []
list1.add(0, “First”);                    // [First]
list1.add(list1.size(), “Last”);          // [First, Last]

We can replace an element at a specified index using the set(int, E) method. The method returns the element that was replaced.

Click here to view code image

System.out.println(“(3) Replace the element at index 1:”);
String oldElement = strList.set(1, “Naan”);
System.out.println(“Element that was replaced: ” + oldElement);   // “Ada”
printListWithIndex(strList); // [0:level, 1:Naan, 2:Java, 3:kayak, 4:Bob,
                             //  5:Rotator, 6:Bob]

We can remove or empty a list of all its elements using the clear() method:

Click here to view code image

// list1 is [First, Last].
list1.clear();                            // []

We can also remove elements from a list, with the list being contracted accordingly.

Click here to view code image

System.out.println(“(4) Remove the element at index 0:”);
System.out.println(“Element removed: ” + strList.remove(0));      // “level”
printListWithIndex(strList); // [0:Naan, 1:Java, 2:kayak, 3:Bob, 4:Rotator, 5:Bob]

System.out.println(“(5) Remove the first occurrence of \”Java\”:”);
System.out.println(“Element removed: ” + strList.remove(“Java”)); // true
printListWithIndex(strList); // [0:Naan, 1:kayak, 2:Bob, 3:Rotator, 4:Bob]

The remove(int) removes the element at the specified index. The method remove(Object) needs to search the list and compare the argument object with elements in the list for object value equality. This test requires that the argument object override the equals() method from the Object class, which merely determines reference value equality. The String class provides the appropriate equals() method. However, the following code will not give the expected result because the String-Builder class does not provide its own equals() method.

Click here to view code image

List<StringBuilder> sbList = new ArrayList<>();
for (String str : wordArray)
  strList.add(str);
System.out.println(sbList); // [level, Ada, kayak, Bob, Rotator, Bob]
StringBuilder element = new StringBuilder(“Ada”);
System.out.println(“Element to be removed: ” + element);          // “Ada”
System.out.println(“Element removed: ” + sbList.remove(element)); // false
System.out.println(sbList); // [level, Ada, kayak, Bob, Rotator, Bob]

Once it is known that an ArrayList<E> will not grow in size, it might be a good idea to trim its capacity down to its size by calling the trimToSize() method, thereby minimizing the storage used by the ArrayList<E>. To reduce the number of times the capacity is increased when adding a large number of elements to the list, appropriate capacity can be set via the ensureCapacity() method before the operation.

Click here to view code image

sbList.trimToSize();           // Capacity is now same as size—that is, 6.
sbList.ensureCapacity(10000);  // Capacity is now large enough for 10000 elements.
                               // Size is still 6.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *