• Post Reply Bookmark Topic Watch Topic
  • New Topic

Hashtable Retrieve  RSS feed

 
Tiago Fernandez
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey, I got a Hashtable with basically 5 keys that stores more than 1 value (same kind of object) into each key. So, when I retrieve the values for one of my 5 keys, how I will get all this values?

Like:

X[] x = (X[]) myHashtable.get(keyNumberOne); // invalid...?

Thanks!
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you store an object into a Hashtable using a key that's already used, the existing object is removed; you're imaginging that Hashtable somehow automatically stores multiple objects for a single key, but it does not.

What you can do, though, is to write a fairly simple subclass of Hashtable (or HashMap, its newer, shinier cousing) which overrides the get and put methods to do something like this automatically -- i.e., create an array or ArrayList to hold the multiple items for a key. I've done it before myself.
 
Tiago Fernandez
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ernest, I didn't know that

I think your solution is very good, but I solved It managing a List into each key. I'm lazy about extending and overriding methods right now

See ya!
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that "decorating" with a Map is almost always preferable to extending an implementation class, such as HashMap.

class X implements Map
{
Map m = new HashMap();

...
}

preferable to:

class X extends HashMap
{

}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!