日期:2014-05-20  浏览次数:20727 次

关于容器的一个有趣话题
List list = new ArrayList();
List vector= new Vector();
 
list.add(1);
list.add(2);
vector.add(3);
vector.add(4);
list.add(vector);
System.out.println(list);
vector.addAll(); //??为什么不能用add()方法
System.out.println(vector);
//输出结果很有意思,但我不明白为什么
//最后一个输出结果如下:1,2,3,4,this connection()

//怎么会有this connection() ????????????????



------解决方案--------------------
this Collection不是this connection

list = [1,2];
vector=[3,4];
list.add(vector);//将vector加入list
list=[1, 2, [3, 4]]


vector.addAll(list);//list里面已经包含了vector,此时再将list添加到vector,可以简单理解为死循环了。
vector=[3, 4, 1, 2, (this Collection)]=[3, 4, 1, 2, [3, 4, 1, 2, [3, 4, 1, 2, (this Collection)]]]
其实this Collection就是vector
------解决方案--------------------
2楼的哥们已经从逻辑说明原因了,具体的代码可以看下面的代码
Vector的toString方法是super.toString(),而具体执行的方法
Java code

/**
     * Returns a string representation of this collection.  The string
     * representation consists of a list of the collection's elements in the
     * order they are returned by its iterator, enclosed in square brackets
     * (<tt>"[]"</tt>).  Adjacent elements are separated by the characters
     * <tt>", "</tt> (comma and space).  Elements are converted to strings as
     * by {@link String#valueOf(Object)}.
     *
     * @return a string representation of this collection
     */
    public String 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(", ");
    }
    }