Hi all,
Do you know why the following program cannot get the result -12 1? JVM seems think object n1 and n2 are different. I have alrady override the equals() and hashcode() methods but I still cannot make the JVM think the object n1 and n2 are the same.
Hope someone can help me.
import java.util.*;
class Nearly {
String value;
Nearly(String v) {
value = v;
}
public int hashcode() {
return 1;
}
public boolean equals(Object o) {
if ((o instanceof Nearly)) {
if (value.charAt(0) == ((Nearly) o).value.charAt(0)) return true;
}
return false;
}
public static void main(String[] sss){
Nearly n1 = new Nearly("aaa");
Nearly n2 = new Nearly("aaa");
String s ="-";
if (n1.equals(n2)) s += "1";
if (n1 == n2) s+= "2";
Set <Nearly> set = new HashSet<Nearly>();
set.add(n1);
set.add(n2);
System.out.println(s + " " + set.size());
}
}