为什么 addAll() 不支持将集合的副本添加到集合中?
Why doesn't addAll() support the addition of a collection's copy to the collection?
在一个方法中,我进行了两次调用。第一次调用从另一个方法构造和 returns 一个哈希集。第二次调用将这个新构造的集合添加到现有集合中,作为参数传入此方法。
public static void someMethod(java.util.HashSet<Coordinate> invalidPositions)
{
java.util.HashSet<Coordinate> newSet = SomeClass.getInvalidPositions(x, y);
invalidPositions.addAll(newSet);
}
很多时候,传入的集合,即已有的集合,会添加另一个内容与自己相同的集合!即setOne.equals(setTwo) == true
然而,JavaDocs 没有添加另一组,而是说 addAll()
:
public boolean addAll(Collection c)
Adds all of the elements in the specified collection to this collection (optional operation).
The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this collection, and this collection is nonempty.)
我的理解正确吗?如果两个集合相等,java 不支持一个相加另一个?如果这是真的,有没有理由这样设计语言?
a.equals(b)
不同于 a == b
。
javadoc 的意思是,如果您这样做,行为是未定义的 a.addAll(a)
。 a.addAll(b)
只要是不同的实例就没有问题
在一个方法中,我进行了两次调用。第一次调用从另一个方法构造和 returns 一个哈希集。第二次调用将这个新构造的集合添加到现有集合中,作为参数传入此方法。
public static void someMethod(java.util.HashSet<Coordinate> invalidPositions)
{
java.util.HashSet<Coordinate> newSet = SomeClass.getInvalidPositions(x, y);
invalidPositions.addAll(newSet);
}
很多时候,传入的集合,即已有的集合,会添加另一个内容与自己相同的集合!即setOne.equals(setTwo) == true
然而,JavaDocs 没有添加另一组,而是说 addAll()
:
public boolean addAll(Collection c)
Adds all of the elements in the specified collection to this collection (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this collection, and this collection is nonempty.)
我的理解正确吗?如果两个集合相等,java 不支持一个相加另一个?如果这是真的,有没有理由这样设计语言?
a.equals(b)
不同于 a == b
。
javadoc 的意思是,如果您这样做,行为是未定义的 a.addAll(a)
。 a.addAll(b)
只要是不同的实例就没有问题