How to get the capacity of the ArrayList in Java?

后端 未结 9 851
灰色年华
灰色年华 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条回答
  • You can use Vector instead of ArrayList. Vector supports capacity() method.

    0 讨论(0)
  • 2020-12-05 08:24

    Looking at ArrayList's spec I see no method that provides this information.

    That said, the ensureCapacity method does seem like a step in the right direction (caution: it is does not guarantee a correct answer): When called it ensures that the capacity is at least the specified argument. So, if the ArrayList implementation uses this method to ensure capacity (as opposed to calling some private method/manipulating the relevant fields directly) you can obtain the current capacity by overriding this method. You also need to override trimToSize() in a similar manner.

    Of course, this solution is not very portable as a different implementation of ArrayList (on a JVM from another vendor) may do things differently.

    Here's how the code should look like

    public class CapacityTrackingArrayList<T> extends ArrayList<T> {
    
       // declare a constructor for each ArrayList constructor ...
    
    
       // Now, capacity tracking stuff:
       private int currentCapacity = 10;
    
       public int getCapacity() { return currentCapacity; }
    
       public void ensureCapacity(int arg) {
         currentCapacity = arg;
         super.ensureCapacity(arg);
       }
    
       public void trimToSize() { currentCapacity = size(); super.trimToSize(); }
    
    }
    
    0 讨论(0)
  • 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 <E> int getArrayListCapacity(ArrayList<E> arrayList) {
            try {
                final E[] elementData = (E[]) field.get(arrayList);
                return elementData.length;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题