How to get the capacity of the ArrayList in Java?

后端 未结 9 875
灰色年华
灰色年华 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: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 extends ArrayList {
    
       // 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(); }
    
    }
    

提交回复
热议问题