Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hashtable- simple

 
NILESH PATEL
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear friends,
I wrote a simple test program, which uses Hashtable and its put(xx,xx) and get(xx) methods. code looks like this:
Hashtable table = new Hashtable();
table.put("name", "nilesh");
table.put("name", "hemen");
table.put("name", "Piyush");
for (int i=0; i<table.size(); i++)
{
System.out.println("NAME IS: " + table.get("name"));
}
My output was:
NAME IS: Piyush
I need output to be:
NAME IS: nilesh
NAME IS: hemen
NAME IS: Piyush
Is there anythig else I can use which would allow me to put multiple entries for same keys. and return output as required.
Thanks in advance
Nilesh
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to the Map Interface javadoc:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

Therefore, if you put a key/value pair into a map and later try to put another key/value pair that uses the same key, you'll simply replace the previous value with the new one. That's why your output is only displaying the last value. The other two were wiped out.
What you can do, however, is have each key map to a list, rather than a single String, like this:

I hope that helps,
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic