ArrayList automatically adding null items

2019-02-22 04:23发布

问题:


Hello everyone. I'm making a vocabulary App, in which I need to create a List<String> (or ArrayList). To do so, I've created the following piece of code (just an example):

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

I've also tried the following:

tempSOLUTION.add(new String(temp));

Both of them add the item to the list, but while debugging, I find that it's array has 12 objects, which are the following:

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

My problem is that I cannot have those null items, as this new list is the key on a HashableMap<String>, so any change will cause an exception, as the key would NOT exist.

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

How can I add an item to the list without creating all those null items?

After having searched, I found an answer on how to remove these null items, which is:

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

But it does not work for my purpose.

Thanks in advance.

回答1:

You're probably looking at its internal array with the debugger. That doesn't matter; it's just an implementation detail.

What matters is what's visible through its public API. In other words, what calls to size() (and so on) tell you. (And if that doesn't return 1 in your code example, then something weird is going on!)



回答2:

From your screenshot it is clear that what is exactly

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

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

This buffer has a greater size than the actual size of the ArrayList because otherwise, every time that you add a new element, the whole objectData should be reallocated as a larger array and all elements copied, but this is surely expensive.

Follow Oli's advice, just ignore the implementation details and trust only the interface.