Java:拒绝在NavigableSet中添加相同的对象
这是我的密码: 导入java.util.*Java:拒绝在NavigableSet中添加相同的对象,java,set,Java,Set,这是我的密码: 导入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&
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());
}
}
如您所见,我没有覆盖Shape
对象上的equals()
方法。我觉得奇怪的是,当我试图在NavigableSet
中添加另一个名为“square”的Shape
对象时,它以某种方式拒绝了它。是因为Shape实现了Comparable
,所以它使用重写的compareTo()
方法来确定方法的相等性
基本上,我想问的是NavigableSet如何确定我试图添加一个重复的对象,而事实上,我没有覆盖equals()方法。没有使用equals()
来比较元素。它使用可比较的
界面
从:
TreeSet
实例使用其compareTo
(或compare
)方法执行所有元素比较,因此从集合的角度来看,此方法认为相等的两个元素是相等的
正如文档中还指出的,如果您希望您的集合遵守常规的set
合同,您必须以与compareTo()
一致的方式定义equals()
:
即使集合的顺序与equals不一致,集合的行为也是定义良好的;它只是没有遵守集合
接口的总合同
另一方面,HashSet
确实使用了equals()
和hashCode()
,并且不注意compareTo()
这就解释了行为上的差异
简而言之,为了使您的元素尽可能广泛地兼容,请确保覆盖
equals()
和hashCode()
,并实现Comparable
接口。也许问题很快就被编辑好了。对于HashSet
,需要equals
和hashCode
。应与比较一致
。我相信在OracleJavaSE8中使用HashSet
可以获得奇怪的行为。
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