ArrayList自动添加空项 [英] ArrayList automatically adding null items

查看:97
本文介绍了ArrayList自动添加空项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




大家好。
我正在制作一个词汇应用程序,我需要创建一个
List< String> (或ArrayList)。为此,我创建了以下代码片段(仅作为示例):

 列表与LT;字符串> tempSOLUTION = new ArrayList< String>(); 
String temp =abc123;
tempSOLUTION.add(temp);

我也尝试了以下内容:



< pre class =lang-java prettyprint-override> tempSOLUTION.add(new String(temp));

他们都将项目添加到列表中,但在调试时,我发现它的数组有12个对象,如下所示:

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

我的问题是我不能拥有那些null项,因为这个新列表是 HashableMap< String> 的键,所以任何更改都会导致异常,因为密钥不存在。



使用调试器的列表(tempSOLUTION)详细信息的屏幕截图: http:/ /www.pabloarteaga.es/stackoverflow.jpg



如何在不创建所有空项目的情况下将项目添加到列表中?



搜索完成后,我找到了如何删除这些空项的答案,其中包括:

  tempSOLUTI ON.removeAll(Collections.singleton(空)); 

但它不能用于我的目的。



提前致谢。

解决方案

您可能正在使用调试器查看其内部数组。那没关系;它只是一个实现细节。



重要的是通过其公共API可见的内容。换句话说,什么调用 size()(等等)告诉你。 (如果你的代码示例中没有返回 1 ,那么会发生一些奇怪的事情!)



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.

解决方案

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

这篇关于ArrayList自动添加空项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆