我正在阅读 Java 8 集合接口(interface)文档。我注意到 Java 8 Collection Interface在未包含在 Java 7 Collection Interface 中的描述中添加了这一段.
Some collection operations which perform recursive traversal of the collection may fail with an exception for self-referential instances where the collection directly or indirectly contains itself. This includes the clone(), equals(), hashCode() and toString() methods. Implementations may optionally handle the self-referential scenario, however most current implementations do not do so.
我对为什么包含这一段感到有些困惑。是因为 Java 7 不能有直接或间接包含自身的集合的自引用实例吗?然后 Java 8 引入了新的接口(interface)或一些允许这样做的新特性?
我正在寻找详细的解释,如果您包含一个示例来说明您的观点,那就太好了。
最佳答案
toString()
List
的格式已指明;它必须递归 toString()
内容并将它们呈现在由 [ ... ]
分隔的逗号分隔列表中.如果您创建 List
如下:
List<Object> list = new ArrayList<>();
list.add(list);
System.out.println(list);
toString()
的幼稚实现会抛出 StackOverflowError
(试试看。)Collection
在某些情况下,实现会尝试针对某些核心方法来防御这个问题;这就是本段所说的。
关于java-8 - Java 8 与 Java 7 集合接口(interface) : self-referential instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45743814/