ArrayList 自动添加空项 [英] ArrayList automatically adding null items
问题描述
大家好.我正在制作一个词汇应用程序,我需要在其中创建一个List
(或 ArrayList).为此,我创建了以下代码段(仅作为示例):
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);
我还尝试了以下方法:
tempSOLUTION.add(new String(temp));
他们都把item加入到list中,但是调试的时候发现它的array有12个对象,如下:
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]
我的问题是我不能拥有那些空项目,因为这个新列表是 HashableMap
上的键,所以任何更改都会导致异常,因为键不存在.
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.
使用调试器的列表 (tempSOLUTION) 详细信息的屏幕截图:http://www.pabloarteaga.es/stackoverflow.jpg
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));
但它不适合我的目的.
提前致谢.
推荐答案
您可能正在使用调试器查看其内部数组.没关系;这只是一个实现细节.
You're probably looking at its internal array with the debugger. That doesn't matter; it's just an implementation detail.
重要的是通过其公共 API 可见的内容.换句话说,对 size()
(等等)的调用会告诉你什么.(如果在您的代码示例中没有返回 1
,那么就会发生一些奇怪的事情!)
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!)
这篇关于ArrayList 自动添加空项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!