Link to home
Start Free TrialLog in
Avatar of brunoguimaraes
brunoguimaraesFlag for Brazil

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!
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of harshgrover
harshgrover

This would not work.

Java uses pass by reference. so, when you are saying "hashtable.put(new Key(field1,field2),value);", it effectively would mean that you are adding a key value pair to the hash table, with the key as the address of (new Key (field1, field2) ).

when you try to do a "hashtable.get(new Key(field1,field2),value);" ; the address assigned to the new class is different. So that is the reason you are getting a null.

Any particular reason why you need to pass the object as a key in the hash table?
> Java uses pass by reference
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

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
Avatar of brunoguimaraes

ASKER

Hey,

I implemented hashCode and equals and now it works perfectly.

Thanks guys!
:-)