Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

java - ArrayList behavior with and without adding an empty string

A newly created ArrayList without adding any elements to it looks just like an ArrayList with an empty string added in it.

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);//[]
    }
}

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:

  1. 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.
  2. Printing out a newly created ArrayList should not be allowed, it should just print NULL or something instead of showing [] like it shows now
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(", ");
    }
}

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 [, , , , ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...