T
twizansk
Hello,
I am having a problem using a hashset for user defined objects.
Identical objects are not being recognized as identical.
Here is the relevant code:
import java.util.*;
class MyString {
MyString(String s, int i) {
this.s=s;
this.i=i;
}
private String s;
private int i;
public boolean equals(MyString mystring) {
return (s.equals(mystring.s) && i==mystring.i);
}
public int hashCode() {
int result=1;
result=37*result + i;
result=37*result + s.hashCode();
return result;
}
}
public class Temp {
public static void main(String[] args) {
MyString key1 = new MyString("ten",10);
MyString key2 = new MyString("ten",10);
HashSet<MyString> hset = new HashSet<MyString>();
hset.add(key1);
System.out.println("hashset contains key1: " + hset.contains(key1));
System.out.println("hashset contains key2: " + hset.contains(key2));
System.out.println("key1.equals(key2): " + key1.equals(key2));
System.out.println("key2.equals(key1): " + key2.equals(key1));
System.out.println("key1 hashcode: " + key1.hashCode());
System.out.println("key2 hashcode: " + key2.hashCode());
}
}
The output is:
hashset contains key1: true
hashset contains key2: false
key1.equals(key2): true
key2.equals(key1): true
key1 hashcode: 116456
key2 hashcode: 116456
Apparently, the hashset doesn't realize that key1 and key2 are equal
even though the hash codes are equal and the equals method is
implemented correctly.
Does anyone know what I'm doing wrong?
Thanks
I am having a problem using a hashset for user defined objects.
Identical objects are not being recognized as identical.
Here is the relevant code:
import java.util.*;
class MyString {
MyString(String s, int i) {
this.s=s;
this.i=i;
}
private String s;
private int i;
public boolean equals(MyString mystring) {
return (s.equals(mystring.s) && i==mystring.i);
}
public int hashCode() {
int result=1;
result=37*result + i;
result=37*result + s.hashCode();
return result;
}
}
public class Temp {
public static void main(String[] args) {
MyString key1 = new MyString("ten",10);
MyString key2 = new MyString("ten",10);
HashSet<MyString> hset = new HashSet<MyString>();
hset.add(key1);
System.out.println("hashset contains key1: " + hset.contains(key1));
System.out.println("hashset contains key2: " + hset.contains(key2));
System.out.println("key1.equals(key2): " + key1.equals(key2));
System.out.println("key2.equals(key1): " + key2.equals(key1));
System.out.println("key1 hashcode: " + key1.hashCode());
System.out.println("key2 hashcode: " + key2.hashCode());
}
}
The output is:
hashset contains key1: true
hashset contains key2: false
key1.equals(key2): true
key2.equals(key1): true
key1 hashcode: 116456
key2 hashcode: 116456
Apparently, the hashset doesn't realize that key1 and key2 are equal
even though the hash codes are equal and the equals method is
implemented correctly.
Does anyone know what I'm doing wrong?
Thanks