‘size’ specifies number of elements in the list, whereas capacity specifies how many elements the list can accommodate.
For example,
List<Integer> list = new ArrayList<> (10);
Above statement defines an ArrayList of capacity 10 and size 0.
Let’s add one element to ArrayList.
list.add(23);
When you add one element to the list, size becomes 1 and capacity becomes 10.
What if you are inserting more elements greater than list capacity?
A new Array with more capacity is created to allocate more elements. All the existing elements of list are copied to new array (List is backed by an array).
As you understand the difference between size and capacity, let me explain how to get the capacity of an ArrayList. When I see the Java documentation, I do not see any method to get the capacity of ArrayList..But do not worry, we can get the capacity using reflections.
As per the Java documentation, Java use the field ‘elementData’ to store the list elements. By calculating this array size, we can get the capacity of ArrayList.
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData;
Below snippet, is used to get the capacity of ArrayList.
private static Field capacityField;
static {
setAccessibilityToCapacity();
}
private static void setAccessibilityToCapacity() {
try {
capacityField = ArrayList.class.getDeclaredField("elementData");
capacityField.setAccessible(true);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
@SuppressWarnings("unchecked")
public static <E> int getArrayListCapacity(ArrayList<E> arrayList) {
try {
final E[] elementData = (E[]) capacityField.get(arrayList);
return elementData.length;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Find the below working application.
ArrayListCapacity1.java
package com.sample.app.collections;
import java.lang.reflect.Field;
import java.util.ArrayList;
public class ArrayListCapacity1 {
private static Field capacityField;
static {
setAccessibilityToCapacity();
}
private static void setAccessibilityToCapacity() {
try {
capacityField = ArrayList.class.getDeclaredField("elementData");
capacityField.setAccessible(true);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
@SuppressWarnings("unchecked")
public static <E> int getArrayListCapacity(ArrayList<E> arrayList) {
try {
final E[] elementData = (E[]) capacityField.get(arrayList);
return elementData.length;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String args[]) {
ArrayList<Integer> arrayList = new ArrayList<>(10);
System.out.println("size -> " + arrayList.size());
System.out.println("capacity -> " + getArrayListCapacity(arrayList));
System.out.println("\nAdd two elements to the list\n");
arrayList.add(10);
arrayList.add(11);
System.out.println("\nsize -> " + arrayList.size());
System.out.println("capacity -> " + getArrayListCapacity(arrayList));
System.out.println("\nAdd 10 more elements to the list\n");
for (int i = 0; i < 10; i++) {
arrayList.add(i);
}
System.out.println("\nsize -> " + arrayList.size());
System.out.println("capacity -> " + getArrayListCapacity(arrayList));
}
}
Output
size -> 0 capacity -> 0 Add two elements to the list size -> 2 capacity -> 10 Add 10 more elements to the list size -> 12 capacity -> 15
You may like
Java: Get all the indexes of occurrence of a substring
Java: How to replace a value in ArrayList or LinkedList
Why do we declare logger with static and final?
No comments:
Post a Comment