How to get the capacity of the ArrayList in Java?

后端 未结 9 885
灰色年华
灰色年华 2020-12-05 07:47

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 t

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 08:25

    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  int getArrayListCapacity(ArrayList arrayList) {
            try {
                final E[] elementData = (E[]) field.get(arrayList);
                return elementData.length;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
    
        }
    }
    

提交回复
热议问题