0

As the title says is there a simple way to change the key of my hashmap?

Here I update all the values of my hashmap

stock.put(itemCode.getText(), new StockData.Item(itemName.getText(),(Double) priceS.getValue(), (Integer)quantityS.getValue(), file.getName())); 

and now I would like to change the key, I used earlier removing and inserting data that worked but the order was changed which I don't want to happen.

1
  • 1
    A HashMap has no order. What do you mean by "the order was changed"? Commented Feb 21, 2016 at 14:47

3 Answers 3

3

If you want to use a HashMap, your keys should never change after insertion.

If the order matters to you, you should be using an implementation of a SortedMap (e.g. TreeMap) instead.

Sign up to request clarification or add additional context in comments.

Comments

1

I don't think you can. A HashMap has no order, objects are inserted based on the hash value of the key, if you change the key, you change its hash and thus the bucket it appears in inside the HashMap. If you want to order the map you are better off using a TreeMap

We hit this problem moving from Java 7 to Java 8 several tests asserted the contents of a HashMap based on the HashMaps toString value, this has no determined order, but under Java 7 it seemed to work but the tests failed under Java 8.

3 Comments

Or a LinkedHashMap - depends what the OP want.
"several tests asserted the contents of a HashMap based on the HashMaps toString value". Ooops...
@BoristheSpider yeah! Tell me about it :S
1

HashMap doesn't guarantee the order of the items, their location inside the HashMap is determined by the hashcode which is calculated from the key. Therefor changing the key will change the location, as you actually removing the previous key value entry and inserting a new entry.

From HashMap documentation

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.