[英]Java: Adding the same object in a NavigableSet rejected
这是我的代码:
导入java.util。*;
public class AnotherBackedCollectionsTest{
public static void main(String... args){
Shape square = new Shape("square");
Shape circle = new Shape("circle");
Shape triangle = new Shape("triangle");
NavigableSet<Shape> shapes = new TreeSet<Shape>();
shapes.add(square);
shapes.add(circle);
shapes.add(triangle);
System.out.println("New shape added? " +shapes.add(new Shape("square")));
for(Shape s : shapes){
System.out.println(s.getName());
}
Set<Shape> shapes2 = new HashSet<Shape>();
shapes2.add(square);
shapes2.add(triangle);
shapes2.add(circle);
System.out.println("New shape added? " +shapes2.add(new Shape("square")));
for(Shape s : shapes2){
System.out.println(s.getName());
}
}
}
class Shape implements Comparable<Shape>{
private String name;
public Shape(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public int compareTo(Shape shape){
return this.name.compareTo(shape.getName());
}
}
我得到以下输出:
New shape added? false
circle
square
triangle
New shape added? true
triangle
square
square
circle
如您所见,我没有在Shape
对象上覆盖equals()
方法。 我发现这很奇怪,是当我尝试在NavigableSet
添加另一个名称为“ square”的Shape
对象时,它以某种方式拒绝了它。 是因为Shape implements Comparable<T>
所以它使用了重写的compareTo()
方法来确定方法的相等性?
基本上,我要问的是NavigableSet如何确定我要添加一个重复的对象,实际上,我没有覆盖equals()方法。
TreeSet
不使用equals()
比较元素。 它使用Comparable
接口。
从文档中 :
TreeSet
实例使用其compareTo
(或compare
)方法执行所有元素比较,因此从集合的角度来看,此方法认为相等的两个元素相等。
正如文档还指出的那样,如果您希望您的集合遵守常规的Set
合约,则必须以与compareTo()
一致的方式定义equals()
compareTo()
:
即使集合的顺序与equals不一致,它的行为也是明确定义的; 它只是不遵守
Set
接口的一般约定。
另一方面, HashSet
确实使用equals()
和hashCode()
,并且不关注compareTo()
。
这解释了行为上的差异。
简而言之,要使您的元素尽可能广泛地兼容,请确保重写equals()
和hashCode()
,并实现Comparable
接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.