dcsimg
In Hashtable, How can I get a value which the key is mapped...
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Thursday, April 12, 2001 06:42 PM

In Hashtable, I want to retrieve a value with my own defined object as a key. The key is different from original one in the Hashtable, but both are the same class instance and has the same value. For example : class Data{ String name; int id; Data(String n, int i){ name = n; id = i; } } .... Hashtable hash = new Hashtable(); Data d1 = new Data("Data",1); Data d2 = new Data("Data",1); hash.put(d1, "value"); String result = (String)hash.get(d2); the result is null but I want to get "value". How can I get it?    More>>

In Hashtable, I want to retrieve a value with my own defined object as a key.
The key is different from original one in the Hashtable, but both are the same class instance and has the same value.

For example :
class Data{
String name;
int id;
Data(String n, int i){
name = n;
id = i;
}
}
....
Hashtable hash = new Hashtable();
Data d1 = new Data("Data",1);
Data d2 = new Data("Data",1);
hash.put(d1, "value");
String result = (String)hash.get(d2);

the result is null but I want to get "value".
How can I get it?

   <<Less

Re: In Hashtable, How can I get a value which the key is mapped...

Posted By:   Shyam_Chintalapati  
Posted On:   Friday, April 13, 2001 08:41 AM

Just reimplement the equals() and hashCode() methods from
Object class, in your Data class. The equals method should
return true if the contents are deep checked for equals.
The hashCode() method normally takes the address of
object and return it as the int code. Instead, you might want
to generate some int code that is based on the contents
of data, such that for d1 and d2, if they have identical
data, they would return the same hashcode. This will
resolve your problem.
Following is the example, simple code that demos this:


import java.util.*;

class Data
{
public boolean equals(Object o)
{
return true;
}

public int hashCode()
{
return 9999;
}


}

public class hash
{
public static void main(String [] args)
{
Data d1 = new Data();
Data d2 = new Data();

System.err.println("hashcode d1: " + d1.hashCode());
System.err.println("hashcode d2: " + d2.hashCode());

Hashtable ht = new Hashtable();

ht.put (d1, "Something");
// ht.put (d2, "Something Else");
if(ht.get(d2) == null)
{
System.err.println("Couldn't find it!");

}
else
{
System.err.println("Found it!");
}


}

}

Re: In Hashtable, How can I get a value which the key is mapped...

Posted By:   AlessandroA_Garbagnati  
Posted On:   Thursday, April 12, 2001 09:58 PM

Hi,

Well, you can't because the two objects, are not the same.

Try to add this to your code:

System.out.println("D1 = " + d1.toString());

System.out.println("D2 = " + d2.toString());

System.out.println("D1 == D2 = " + d1.equals(d2));
About | Sitemap | Contact