brunoguimaraes
asked on
Problem with Hashtable
Hi,
I have a Hashtable that has a two-field key. I created a class to be the key, a simple bean with 2 fields, getter/setter methods and all that stuff.
So I add a key-value pair to the Hashtable this way:
hashtable.put(new Key(field1,field2),value);
Then I try to retrieve the value this way:
hashtable.get(new Key(field1,field2));
But when I do that, it returns null.
What am I doing wrong?
Thanks in advance!
I have a Hashtable that has a two-field key. I created a class to be the key, a simple bean with 2 fields, getter/setter methods and all that stuff.
So I add a key-value pair to the Hashtable this way:
hashtable.put(new Key(field1,field2),value);
Then I try to retrieve the value this way:
hashtable.get(new Key(field1,field2));
But when I do that, it returns null.
What am I doing wrong?
Thanks in advance!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
> Java uses pass by reference
Java uses pass by value though
Java uses pass by value though
Java manipulates objects by reference and all object variables are references. However, Java does not pass method arguments by reference, it passes them by value.
going by that premise, new Key(field1, field2) would be a reference, not a value
going by that premise, new Key(field1, field2) would be a reference, not a value
>>going by that premise, new Key(field1, field2) would be a reference, not a value
Every object created gets a reference. The point here is that unless the methods in question are overridden, the lookup won't work unless the original reference is used to do it.
Every object created gets a reference. The point here is that unless the methods in question are overridden, the lookup won't work unless the original reference is used to do it.
And thats because Object.equals() only performs reference equality
ASKER
Hey,
I implemented hashCode and equals and now it works perfectly.
Thanks guys!
I implemented hashCode and equals and now it works perfectly.
Thanks guys!
:-)
Java uses pass by reference. so, when you are saying "hashtable.put(new Key(field1,field2),value);
when you try to do a "hashtable.get(new Key(field1,field2),value);
Any particular reason why you need to pass the object as a key in the hash table?