Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList automatically adding null items


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.

like image 677
vagaerg Avatar asked Aug 25 '13 23:08

vagaerg


1 Answers

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!)

like image 149
Oliver Charlesworth Avatar answered Oct 20 '22 19:10

Oliver Charlesworth