Results 1 to 3 of 3
- 05-06-2012, 12:07 PM #1
Member
- Join Date
- Oct 2011
- Posts
- 30
- Rep Power
- 0
HashMap help? Values keep overriding..?
I create a new hashMap : private HashMap<String, LibraryItem> itemsMap;
This is to store a string and then a LibraryItem object.
Constructor: itemsMap = new HashMap<String, LibraryItem>();
public void storeLibraryItem(LibraryItem li)
{
itemsMap.put(new String ("Item"), li);
}
It compiles fine, but each of my LibraryItem li objects keep overriding each other until the last one.
I don't really want to keep adding new .put each time for eg:
itemsMap.put(new String ("Item"), li);
itemsMap.put(new String ("Item"), li);
itemsMap.put(new String ("Item"), li);
(For each different object because the storeLibraryItem method gets called when I read a file)
Thanks very much!
-
Re: HashMap help? Values keep overriding..?
This is equivalent to your writing an English-Spanish dictionary that looks like this:
hello -- hola
hello -- adiós
hello -- gracias
hello -- de nada
hello -- hoy
...
That wouldn't be a very useful dictionary, and no Spanish speaker would be able to use to help them translate an article in English.
It's the same for a HashMap -- each key *must* be unique, else it doesn't function. So do that, make each key unique and meaningful, else simply use an ArrayList.
- 05-06-2012, 12:59 PM #3
Re: HashMap help? Values keep overriding..?
Another way to look at it. What if you are assigning values to a variable:objects keep overriding each other until the last one.
var = val1;
var = var2;
var = val3;
Here the values are overriding the previous ones until the last one.
If you test what is returned by the put() method you will see if you are replacing an existing value. See the API doc.If you don't understand my response, don't ignore it, ask a question.
Similar Threads
-
HashMap example - looking for and printing out the same values
By adize in forum New To JavaReplies: 1Last Post: 03-01-2012, 07:51 PM -
Cannot return values from hashmap
By uhertz in forum New To JavaReplies: 1Last Post: 06-17-2011, 04:16 PM -
how to get the values from hashmap
By baktha.thalapathy in forum New To JavaReplies: 5Last Post: 05-25-2010, 02:12 PM -
HashMap contains all values but doesn't show all values
By xcallmejudasx in forum New To JavaReplies: 3Last Post: 05-10-2009, 11:35 PM -
how to return values from hashmap
By oregon in forum New To JavaReplies: 2Last Post: 08-01-2007, 04:56 PM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks