• Post Reply Bookmark Topic Watch Topic
  • New Topic

Hashtable  RSS feed

 
Chennarao Marvatu
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The requirement is to use a user defined object as a key. But I want the hash table to consider two user defined objects with same values as single key.
What is the best solution to print �value of 10� and null as output for the two print statements? look at this code

import java.util.Hashtable;

/**
* Simple key Class
*
* @author
* @version
*/
class Key {
private int i;
private String s;

Key(int i, String s) {
this.i = i;
this.s = s;
}

public int getI() {
return i;
}

public String getS() {
return s;
}
}

public class TestHash {
public static void main(String[] args) {
Hashtable ht = new Hashtable();

ht.put(new Key(10, "I am 10"), "Value of 10");
System.out.println("Get with Same key different object: " + ht.get(new Key(10, "I am 10")));
System.out.println("Get with another key: " + ht.get(new Key(11, "I am 10")));
}
}


Thanks
Chennarao
 
Manoj Zachariah
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
create an oject for key and use it in get()

 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are using your own class as a key, one thing has to be kept in mind, this custom class has to override hashcode() and equals() method properly other wise you wont land up in getting a proper valuue for a key.
String & other Wrapper classes overrides these methods & hence these can be used as keys in Hashtable.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!