【问题标题】:How toString() of AbstractCollection prints a Collection within Collection in Java?AbstractCollection 的 toString() 如何在 Java 中的 Collection 中打印 Collection?
【发布时间】:2017-02-26 18:10:51
【问题描述】:
List subitemsCategory=new ArrayList(); //Creating the subList
subitemsCategory.add("Garnier");       //Adding sublist
subitemsCategory.add("Bajaj");
List items=new ArrayList();            //Creating Main List
items.add("Shampoo");
items.add("Oil");
items.add(subitemsCategory);           //Adding a new List in items
System.out.println(items);             //Print Collection within Collection

如何打印集合中的集合?

【问题讨论】:

  • 类型参数。你应该使用它们。 (这也可能有助于您了解您的问题。)
  • 看源码:hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/…。它调用append(e),其中e是列表的一个元素,所以它基本上使用e.toString()
  • sb.append(e == this ? "(this Collection)" : e); //这里("this Collection")的目的是什么?
  • "this Collection" 被附加到 StringBuilder,这意味着该集合包含对自身的引用

标签: java collections


【解决方案1】:

通过toString递归调用。
在 Java 中,toString 方法可以在每个对象上调用,无论它是否是列表。

由 3 个字符串 "a""b""c" 组成的列表以这种方式打印: [a, b, c].
[ 打印在元素之前,
然后打印一个逗号分隔的列表
最后有一个]

当一个元素本身是一个列表时会发生什么? 它的toString方法被执行,因此:
[a, b, [c, d, e]]

在你的情况下:

[Shampoo, Oil, [Garnier, Bajaj]]

在 OP 的另一个问题之后... 当我们这样做时会发生什么:

Collection aCollection = //constructor call
aCollection.add(aCollection);

没有堆栈溢出等错误。 它只会打印:

[..., (this Collection), ...]

这就是使用三元运算符in the source code的目的。

【讨论】:

  • sb.append(e == this ? "(this Collection)" : e); //这里的“这个集合”的作用是什么?
  • @SunnyAgrawal,如果你在你的代码中这样做:items.add(items),你会看到 ;) 它避免了对同一个集合的无限引用。
猜你喜欢
  • 1970-01-01
  • 2011-05-13
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 2013-01-23
相关资源
最近更新 更多