P
pembed2003
Hi all,
I have been trying to do something really simple but I could find any
solutions to it! I have the following:
class P{
int id;
P(int i){id = i;}
public int hashCode(){return id;}
public boolean equals(P o){return id = o.id;}
public static void main(String[] args){
HashMap m = new HashMap();
m.put(new P(1),new Integer(1));
m.put(new P(1),new Integer(2));
Set k = m.entrySet();
Iterator i = k.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
The program prints out 2 lines which I am not sure I understand. My P
class has a hashCode method which simply returns the id of the object.
I put 2 'new P(1)' instance into m but why doesn't HashMap reject the
second one or overwrite the first one becasue they have the same hash
code??? I though the purpose of hashCode is to let you reject or
detect dup objects, no?
In generaly, I found it difficult to do something like:
//
// insert a bunch of objects into a HashMap
//
later:
//
// how to check if HashMap has a P object with id 1???
//
this:
if(m.containsKey(new P(1)){
}
ALWAYS return false even I have a lot of P objects with id 1! How do I
solve that? Thanks!
I have been trying to do something really simple but I could find any
solutions to it! I have the following:
class P{
int id;
P(int i){id = i;}
public int hashCode(){return id;}
public boolean equals(P o){return id = o.id;}
public static void main(String[] args){
HashMap m = new HashMap();
m.put(new P(1),new Integer(1));
m.put(new P(1),new Integer(2));
Set k = m.entrySet();
Iterator i = k.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
The program prints out 2 lines which I am not sure I understand. My P
class has a hashCode method which simply returns the id of the object.
I put 2 'new P(1)' instance into m but why doesn't HashMap reject the
second one or overwrite the first one becasue they have the same hash
code??? I though the purpose of hashCode is to let you reject or
detect dup objects, no?
In generaly, I found it difficult to do something like:
//
// insert a bunch of objects into a HashMap
//
later:
//
// how to check if HashMap has a P object with id 1???
//
this:
if(m.containsKey(new P(1)){
}
ALWAYS return false even I have a lot of P objects with id 1! How do I
solve that? Thanks!