Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to compine two hash tables?

 
Sultan Al-Yahyai
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 20902
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
Robert Hayes
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try putall() and/or read the java.util docs...
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
doh, missed that one
 
Sultan Al-Yahyai
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hashtable implements the Map interface, so it should work:

 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic