• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Hashtable

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
create an oject for key and use it in get()

 
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic