java - 识别 HashSet 中的重复项

标签 java object addition hashset

所以,我用 Java 编写了这段代码:

import java.util.HashSet;

class Interval{
  long from;
  long to;

  public Interval(long from, long to) {
    this.from = from;
    this.to = to;
  }

  public boolean equals(Interval other) {

    return from == other.from && to == other.to;
  }


 }

public class Test {

   public static void main(String[] args) {

       HashSet<Interval> mySet  = new HashSet<Interval>();

       mySet.add(new Interval(1,2));
       mySet.add(new Interval(1,2));

       for(Interval in : mySet) {
        System.out.println(in.from + " " + in.to);
       }
   }

 }

问题是集合无法识别已经存在从 1 到 2 的区间。我定义了函数 equals,但它仍然不起作用。我尝试实现 Comparable 接口(interface)并重载compareTo 函数,但还是一无所获。有人可以告诉我如何解决这个问题吗?

谢谢!

最佳答案

您需要从 java.lang.Object 重写 equals

您没有,因为您的不接受对象作为参数。

public boolean equals(Object obj) {
    if (obj == null)
        return false;
    else if (this.getClass() != obj.getClass())
        return false;
    else {
        Interval other = (Interval) obj;
        return from == other.from && to == other.to;
    }
}

对于 hashCode,您可以这样做。

public int hashCode() {
    return new Long(this.from).hashCode();
}

所以总的来说,你得到了这段代码。

import java.util.HashSet;

class Interval {
    long from;
    long to;

    public Interval(long from, long to) {
        this.from = from;
        this.to = to;
    }

    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        else if (this.getClass() != obj.getClass())
            return false;
        else {
            Interval other = (Interval) obj;
            return from == other.from && to == other.to;
        }
    }

    public int hashCode() {
        return new Long(this.from).hashCode();
    }
}

public class Test003 {

    public static void main(String[] args) {

        HashSet<Interval> mySet = new HashSet<Interval>();

        mySet.add(new Interval(1, 2));
        mySet.add(new Interval2(1, 2));

        for (Interval in : mySet) {
            System.out.println(in.from + " " + in.to);
        }
    }

}

关于java - 识别 HashSet 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21237270/

相关文章:

cakephp - CakePHP Controller 中的 add 方法不起作用

c++ - 如果两者都会给出相同的结果,我应该更喜欢加法运算符还是逻辑 OR 运算符?

java - 打印已包含值的数组

java - JNI问题: calling in Java a Dll that uses a third party dll

java - 如何转换 for 循环以找到 Java 流的第一次出现?

javascript - 如何在 Javascript 中制作自定义对象?

java正则表达式解析部分标题标签

Javascript 数组和对象/类

Java:可以访问由字符串连接创建的临时对象吗?

iphone - 在 iOS 中将事件添加到生日日历