带有和不添加空字符串的ArrayList行为 [英] ArrayList behavior with and without adding an empty string
问题描述
一个新创建的 ArrayList
,不添加任何元素,看起来就像一个 ArrayList
,其中添加了一个空字符串.
A newly created ArrayList
without adding any elements to it looks just like an ArrayList
with an empty string added in it.
这使我感到即使未在其中添加任何元素的情况下,新创建的 ArrayList
仍具有默认的空 string
或其中添加的元素.
This makes me feel that a newly created ArrayList
even without adding any elements in it has a default empty string
or element added in it.
package cracking;
import java.util.ArrayList;
public class Ask
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
System.out.println(al.size());//0
System.out.println(al);//[]
al.add("");
System.out.println(al.size());//1
System.out.println(al);//[]
}
}
但是,在两种情况下 ArrayList
的大小之间的差异使它们不一致,尤其是因为打印时的两个 ArrayList
看起来是相同的.
However, the discrepancy between the size of ArrayList
in the two scenarios makes them inconsistent, especially since the two ArrayList
when printed out look just the same.
为了保持一致性,我觉得两个都不错:
To maintain consistency, I feel, either of two would've been good:
- 刚刚创建的ArrayList的大小,即向其添加任何元素应显示1表示空字符串或元素,因为甚至添加到
ArrayList
都使它看起来相同. - 不允许打印出新创建的
ArrayList
,它会应该只显示NULL或类似内容而不显示[]
现在显示
- The size of the ArrayList which is just created, i.e., even before
adding any element to it should show 1 implying empty string or
element, since even adding to the
ArrayList
makes it look the same. - Printing out a newly created
ArrayList
should not be allowed, it should just print NULL or something instead of showing[]
like it shows now
推荐答案
您被 AbstractCollection
的 toString
实现所迷惑.看到这里:
You are being tricked by the toString
implementation of the AbstractCollection
. See here:
public String More ...toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
您的收藏集的大小为1,但不会打印任何内容,包括逗号字符
,因为它的大小仅为1.尝试添加multilpe空字符串,您将更清楚地看到结果.
Your collection has a size of 1, but it's not printing anything, including the comma character ,
because it only has size one. Try adding multilpe emptry Strings and you'll see the result more clearly.
al.add("");
al.add("");
al.add("");
al.add("");
al.add("");
System.out.println(al); // Prints [, , , , ]
这篇关于带有和不添加空字符串的ArrayList行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!