Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:拒绝在NavigableSet中添加相同的对象_Java_Set - Fatal编程技术网

Java:拒绝在NavigableSet中添加相同的对象

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&

这是我的密码:

导入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());
    }

}
如您所见,我没有覆盖
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