//一个对象被放进了HashSet, 当使用HashSet.contains(Object o)方法时,如果被传入的o 拥有与HashSet中已有对象相同的HashCode,那么这个方法会返回true,但实际上好像不是这么回事.//如下的这个程序自己实现了一个复数(Complex)类,OverRide了其中的hashCode()方法.
//对于 相同的复数(Complex1.x == Complex2.x && Complex1.y == Complex2.y) hashCode方法肯定对返回相同的hash值
package com.dcs.unicom.debug;import java.util.HashSet;public class DebugClass {
public static void main(String[] args) {
HashSet hm = new HashSet();
//首先new 了一个Complex对象
Complex test = new Complex(1, 1);
//将这个对象放入了HashSet
hm.add(test);
System.out.println(test.hashCode());
//用contains方法判断一个相等的复数是否已经被放进了 HashSet中.
System.out.println(hm.contains(new Complex(1, 1)));
System.out.println(hm.contains(test));
}
}class Complex {
private static final int BYTE_MAX = 256;
private int x = 0, y = 0;
public Complex(int x, int y) {
this.x = x >= 0 ? x : x + BYTE_MAX;
this.y = y >= 0 ? y : y + BYTE_MAX;
} public synchronized int hashCode() {
return x + y * BYTE_MAX;
} public String toString() {
return "" + x + " + i" + y;
} public boolean equals(Complex c) {
return c.x == this.x && c.y == this.y;
}
}
//程序(contains(Object o))执行输出总是为false
//不知道这是什么原因,还望高手解答. (100分)
//对于 相同的复数(Complex1.x == Complex2.x && Complex1.y == Complex2.y) hashCode方法肯定对返回相同的hash值
package com.dcs.unicom.debug;import java.util.HashSet;public class DebugClass {
public static void main(String[] args) {
HashSet hm = new HashSet();
//首先new 了一个Complex对象
Complex test = new Complex(1, 1);
//将这个对象放入了HashSet
hm.add(test);
System.out.println(test.hashCode());
//用contains方法判断一个相等的复数是否已经被放进了 HashSet中.
System.out.println(hm.contains(new Complex(1, 1)));
System.out.println(hm.contains(test));
}
}class Complex {
private static final int BYTE_MAX = 256;
private int x = 0, y = 0;
public Complex(int x, int y) {
this.x = x >= 0 ? x : x + BYTE_MAX;
this.y = y >= 0 ? y : y + BYTE_MAX;
} public synchronized int hashCode() {
return x + y * BYTE_MAX;
} public String toString() {
return "" + x + " + i" + y;
} public boolean equals(Complex c) {
return c.x == this.x && c.y == this.y;
}
}
//程序(contains(Object o))执行输出总是为false
//不知道这是什么原因,还望高手解答. (100分)
return c.x == this.x && c.y == this.y;
}你没有覆盖掉,应该改为
public boolean equals(Object c) {
return ((Complex)c).x == this.x && ((Complex)c).y == this.y;
}