How does memory allocation of an ArrayList work?

后端 未结 5 1560
遇见更好的自我
遇见更好的自我 2021-02-01 02:49

As far as I know, when we are creating an ArrayList:

ArrayList list = new ArrayList(SIZE);

The JVM res

5条回答
  •  时光说笑
    2021-02-01 03:50

    The very first thing I want to correct is, When we are adding new elements into our list, when number of elements reaches 100% of SIZE it reserves a new, contiguous part of memory and copies all of the elements.

    New Size of ArrayList will be:

    NewSize of ArrayList = (CurrentSize * 3/2) + 1

    But going this way is never recommended, if we have idea how much objects needs to be stored then we can use following constructor of ArrayList:-

    ArrayList ar = new ArrayList(int initialCapacity);

    If our JVM couldn't specify enough contiguous space on heap for the ArrayList, At runtime we'll get

    • Runtime error: OutOfMemoryError

提交回复
热议问题