我正在編寫一個簡單的程序如下:給定兩個數字M和N,p來自[M,N],q來自[1,p-1],找到所有不可縮減的部分p/q。 我的想法是蠻力p,q的所有可能的價值。並使用HashSet來避免重複的部分。但是,包含函數不能按預期工作。Java 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是重複的。任何人都可以幫助我找出爲什麼以及如何解決它。 非常感謝。
讓我們不要忘了'的hashCode()'方法以及:哪些問題應該在Java中覆蓋equals和hashCode時,應考慮?](HTTP://計算器.COM /問題/ 27581 /乜問題,應待考慮-時,壓倒一切的,等於和 - 哈希碼功能於JAVA) – Pshemo