Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the capacity of the ArrayList in Java?

Tags:

Its known that Java ArrayList is implemented using arrays and initializes with capacity of 10 and increases its size by 50% . How to get the current ArrayList capacity not the Size of the ArrayList.

Thx

like image 296
JavaUser Avatar asked Mar 23 '10 01:03

JavaUser


People also ask

How do you find the capacity of an ArrayList?

Default capacity of ArrayList is 10. once the max size is reached,new capacity will be: new capacity=(currentcapacity*3/2)+1. Save this answer.

What is the capacity of an ArrayList Java?

Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold.

How do you find the capacity of a list?

To check capacity in Java, firstly create a list and add elements. After that use ensureCapacity() and increase the capacity. arrList. ensureCapacity(15);


2 Answers

I don't think this is possible. What is your use case? I believe C# ArrayLists have a .capacity property, but the Java ArrayList class doesn't expose this information.

You have the constructor that takes an initial capacity argument, and you have the ensureCapacity() method which you could use to reduce the amount of incremental reallocation.

You also have the trimToSize() method you can use if you are really worried about memory usage.

like image 80
Mark B Avatar answered Nov 17 '22 03:11

Mark B


You can get it by reflection:

public abstract class ArrayListHelper {      static final Field field;     static {         try {             field = ArrayList.class.getDeclaredField("elementData");             field.setAccessible(true);         } catch (Exception e) {             throw new ExceptionInInitializerError(e);         }     }      @SuppressWarnings("unchecked")     public static <E> int getArrayListCapacity(ArrayList<E> arrayList) {         try {             final E[] elementData = (E[]) field.get(arrayList);             return elementData.length;         } catch (Exception e) {             throw new RuntimeException(e);         }      } } 
like image 32
pgras Avatar answered Nov 17 '22 05:11

pgras