This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Hashtable- simple Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Hashtable- simple" Watch "Hashtable- simple" New topic

Hashtable- simple

Ranch Hand

Joined: Nov 21, 2000
Posts: 71
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
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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,

SCJP Tipline, etc.
I agree. Here's the link:
subject: Hashtable- simple
Similar Threads
Using HashMap vs Hastable
Exception in parsing XML file
hashmap and equals doubts
Primitive data types in Hashtables
Running PMD from commandline : Exporting the output to an external file.