aspose file tools*
The moose likes Java in General and the fly likes How to compine two hash tables? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to compine two hash tables?" Watch "How to compine two hash tables?" New topic
Author

How to compine two hash tables?

Sultan Al-Yahyai
Greenhorn

Joined: Nov 07, 2004
Posts: 7

Hell,
1) I have two hash tables say ht1, ht2
I need the contents of ht2 to me moved/coppied to the end of ht1, how to do so?

regards
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
get the keys from t2.
Iterate over those, and insert the values retrieved into t1.
Something like


Remember that this will replace any value from t1 that has the same key as another value from t2.


42
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

You can't control the location of the entry in the map, and you have issues with duplicate keys, but I think this should work:



Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Robert Hayes
Ranch Hand

Joined: Oct 24, 2004
Posts: 116
Try putall() and/or read the java.util docs...
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
doh, missed that one
Sultan Al-Yahyai
Greenhorn

Joined: Nov 07, 2004
Posts: 7
Thank you all,

t1.putAll(t2); Didn't work
becuase method is not defined .putall(hashtable)!

but
Enumeration e = t2.keys();
while (e.hasMoreElements())
{Object o = e.nextElement();
t1.put(o, t2.get(o));
}
worked fine
thanks
Sultan Al-Yahyai
Greenhorn

Joined: Nov 07, 2004
Posts: 7
Hi,
Also I tried this one and it worked
Enumeration e=t1.elements();
Enumeration k=t1.keys();
while ( k.hasMoreElements() )
{ t2.put(k.nextElement(),e.nextElement());
}
Robert Hayes
Ranch Hand

Joined: Oct 24, 2004
Posts: 116
Hashtable implements the Map interface, so it should work:

Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
Originally posted by Sultan AL-Yahyai:
Thank you all,

t1.putAll(t2); Didn't work
becuase method is not defined .putall(hashtable)!


putall isn't there, but putAll is.
Unless you're using a really really old compiler that is, 1.1 or earlier.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to compine two hash tables?