ArrayList automatically adds null elements


Welcome all. I am making an App dictionary in which I need to create a List<String> (or ArrayList). To do this, I created the following code snippet (just an example):

 List<String> tempSOLUTION = new ArrayList<String>(); String temp = "abc123"; tempSOLUTION.add(temp); 

I also tried the following:

 tempSOLUTION.add(new String(temp)); 

Both of them add an item to the list, but during debugging, I find that this array has 12 objects, which are as follows:

 [abc123, null, null, null, null, null, null, null, null, null, null, null] 

My problem is that I cannot have these null elements since this new list is the key in the HashableMap<String> , so any change will throw an exception since the key will NOT exist.

Screenshot from the list (tempSOLUTION) using the debugger: http://www.pabloarteaga.es/stackoverflow.jpg

How to add an item to the list without creating all these null items?

After searching, I found an answer on how to remove these null elements, namely:

 tempSOLUTION.removeAll(Collections.singleton(null)); 

But this does not work for my purpose.

Thanks in advance.

+6
source share
2 answers

You are probably looking at your internal array with a debugger. It does not matter; this is just an implementation detail.

What matters is what is visible through its public API. In other words, what size() calls (etc.) call. (And if that does not return 1 in your code example, then something strange happens!)

+15
source

From your screenshot it’s clear what exactly

 [abc123, null, null, null, null, null, null, null, null, null, null, null] 

- this is not the ArrayList itself, but its member variable objectData , which is the internal buffer of the ArrayList (where it actually stores the elements that you add to it).

This buffer is larger than the actual size of the ArrayList , because otherwise, every time you add a new element, the whole objectData needs to be redistributed as a larger array and all elements will be copied, but it is certainly expensive.

Follow Olya’s advice, just ignore implementation details and trust only the interface.

+6
source

Source: https://habr.com/ru/post/952470/


All Articles