欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

对集合类AbstractCollection借口toString方法的this关键字理解,

来源: javaer 分享于  点击 46086 次 点评:40

对集合类AbstractCollection借口toString方法的this关键字理解,



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




ArrayList<ArrayList> a=new ArrayList<ArrayList>();
a.add(a);
System.out.println(a);
时会输出 [(this Collection)]

可见当一个集合类的泛型是其自身 并且把自己假如到自己的集合中去 就会打印 “this Collection”


相关文章

    暂无相关文章

用户点评