In Java 8, why is the default capacity of ArrayList now zero?

前端 未结 6 1409
再見小時候
再見小時候 2020-11-27 13:34

As I recall, before Java 8, the default capacity of ArrayList was 10.

Surprisingly, the comment on the default (void) constructor still says: Cons

6条回答
  •  借酒劲吻你
    2020-11-27 13:56

    In java 8 default capacity of ArrayList is 0 until we add at least one object into the ArrayList object (You can call it lazy initialization).

    Now question is why this change has been done in JAVA 8?

    Answer is to save memory consumption. Millions of array list objects are created in real time java applications. Default size of 10 objects means that we allocate 10 pointers (40 or 80 bytes) for underlying array at creation and fill them in with nulls. An empty array (filled with nulls) occupy lot of memory .

    Lazy initialization postpones this memory consumption till moment you will actually use the array list.

    Please see below code for help.

    ArrayList al = new ArrayList();          //Size:  0, Capacity:  0
    ArrayList al = new ArrayList(5);         //Size:  0, Capacity:  5
    ArrayList al = new ArrayList(new ArrayList(5)); //Size:  0, Capacity:  0
    al.add( "shailesh" );                    //Size:  1, Capacity: 10
    
    public static void main( String[] args )
            throws Exception
        {
            ArrayList al = new ArrayList();
            getCapacity( al );
            al.add( "shailesh" );
            getCapacity( al );
        }
    
        static void getCapacity( ArrayList l )
            throws Exception
        {
            Field dataField = ArrayList.class.getDeclaredField( "elementData" );
            dataField.setAccessible( true );
            System.out.format( "Size: %2d, Capacity: %2d%n", l.size(), ( (Object[]) dataField.get( l ) ).length );
    }
    
    Response: - 
    Size:  0, Capacity:  0
    Size:  1, Capacity: 10
    

    Article Default capacity of ArrayList in Java 8 explains it in details.

提交回复
热议问题