Java: Setting key of a hashmap explicitly and keeping reference to it

public static HashMap<ArrayList<Integer>, String> map = new HashMap<ArrayList<Integer>, String>();  
public static ArrayList<ArrayList<Integer>> keys = new ArrayList<>(map.keySet());

Then in main

map.put(key, "c");

(assume key is a valid ArrayList). But keys still has size 0 after that.

How can I make the relationship of keys stronger so that it will be actually tied to the HashMap and contain all its keys.

Upvotes: 0

Views: 76

Answers (2)

Bohemian
Bohemian

Reputation: 424983

You can't.

Map.keySet() returns the Map's current key set, which you then load into your list. Changes to the map after that have no effect on the contents of the list.


Most people would just re-get the key set if needed. Why don't you just do that?

Upvotes: 0

assylias
assylias

Reputation: 328588

The copy constructor of ArrayList copies all the keys in the map to the ArrayList but if you change the map after that point it will not be reflected.

I can think of 3 options:

  • write your own map implementation that embeds an ArrayList and keeps it up to date
  • update the ArrayList manually everytime you update the map
  • don't use an ArrayList at all (keySet() is there when you need to access the keys so I'm not sure why you would need one)

Upvotes: 3

Related Questions