Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...