ashishraaj ashishraaj - 9 days ago 10
Java Question

In debug mode I can see extra array list elements and are initialized to zero

I am fetching some data from database using simple jdbc call and when I am debugging my application, it is showing some extra record which are null.

enter image description here

Actual size of my list should be 138 but its initializing 171 as array size.

enter image description here

As I am using collection named LDCBeanCollection which extends ArrayList and implements BaseDTO which is Serializable

public class LDCBeanCollection extends ArrayList implements BaseDTO


public interface BaseDTO extends Serializable


Why this problem is occuring. Am I missing something ?

How can I overcome this problem?

Answer

An ArrayList internally manages a backing array that is usually larger than the current size. Since ArrayList is a variable-length list the array size is managed internally so it doesn't have to be reallocated each time you add an element. That would be extremely expensive. When the list overflows (you add more elements that currently fit) the backing array size is incremented by 1.5 times than original size to allow for future expansion.

In other words, there will almost always be extra unused elements at the end of the backing array, and they only consume one reference per entry.

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/ArrayList.java#ArrayList.grow%28int%29

If you are concerned about the extra elements, don't be. The class manages things so they are never seen to be part of the list.