繁体   English   中英

Java HashSet包含无法使用的功能

[英]Java HashSet contains function not working

我正在编写一个简单的程序,如下所示:给定两个数字M和N,p来自[M,N],q来自[1,p-1],求出p / q的所有不可约分数。 我的想法是蛮力p,q的所有可能值。 并使用HashSet避免重复分数。 但是,以某种方式包含的功能不能按预期工作。

我的密码

import java.util.HashSet;
import java.util.Set;

public class Fraction {
    private int p;
    private int q;

    Fraction(int p, int q) {
        this.p = p;
        this.q = q;
    }

    public static int getGCD(int a, int b) {
        if (b == 0)
            return a;
        else 
            return getGCD(b, a % b);
    }

    public static Fraction reduce(Fraction f) {
        int c = getGCD(f.p, f.q);
        return new Fraction(f.p / c, f.q / c);
    }

    public static HashSet<Fraction> getAll(int m, int n) {
        HashSet<Fraction> res = new HashSet<Fraction>();
        for (int p = m; p <= n; p++)
            for (int q = 1; q < p; q++) {
                Fraction f = new Fraction(p,q);
                Fraction fr = reduce(f);
                if (!res.contains(fr))
                    res.add(fr);
            }
        return res;
    }

    public static void print(Fraction f) {
        System.out.println(f.p + "/" + f.q);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HashSet<Fraction> res = getAll(2, 4);
        for (Fraction f : res)
            print(f);
    }

}

这是程序的输出

4/3
3/1
4/1
2/1
3/2
2/1

您可以看到分数2/1是重复的。 任何人都可以帮助我弄清楚为什么以及如何解决它。 非常感谢。

重写Fraction类中的Object#equalsObject#hashCode方法。 HashSet使用这些方法确定两个对象是否相同。 当不覆盖它们时,equals方法将测试对象引用的相等性,而不是其字段值的相等性。

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + p;
    result = prime * result + q;
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Fraction other = (Fraction) obj;
    if (p != other.p)
        return false;
    if (q != other.q)
        return false;
    return true;
}

您需要实现Fraction#equals()Fraction#hashcode() ,因为这用于确定集合中是否包含特定值的天气。 没有它,将比较对象引用,这将无法为您提供所需的结果。

您的Fraction类不会覆盖hashCodeequals HashMap包含尝试查找具有与您提供的hashCode相同(并等于)的hashCode的键。 创建新的Fraction实例时,它永远不会与HashMap已经存在的实例相同。 这是您执行hashCodeequals

@Override
public int hashCode() {
    return super.hashCode() + p * 24 + q * 24;
}

@Override
public boolean equals(Object other) {
    if (!(other instanceof Fraction)) return false;
    return ((Fraction) other).p == this.p && ((Fraction) other).q == this.q;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM