tags:

views:

235

answers:

4

Welcome. I have a generic void method swap that takes a Map and 2 keys. The method will swap the values associated with the keys in the Map. I already checked that both keys are contained in the Map somewhere else, but in this method, I can't use looping. My method answer:

public static<K, W> swap(Map<K,V m, K key1, K key2>){
  m.put(key2, m.put(?)) // I don't really understand what I would have to
                        // put in this part, so how would i have to remember
                        // the 1st key, would I just set the value to
                        // a new initialized key?
}
+1  A: 

This method will swap the values for two keys:

public void swap(Object key1, Object key2, Map map)
{
    Object temp = map.get(key1);
    map.put(key1, map.get(key2));
    map.put(key2, temp);
}

Yes, you do need to save the value for 1 of the keys, otherwise it will be lost when replacing key1's value with key2's.

Outlaw Programmer
ok, so the K is the objects right?
Roxy
+2  A: 

This will swap the values of two keys:

Map<K, V> aMap;

V temp = aMap.get(key1);
aMap.put(key1, aMap.put(key2, temp);
jjnguy
+9  A: 

Use a temporary holder for value:

public static<K, V> swap(Map<K,V> m, K key1, K key2){
  V value = m.get(key1);
  m.put(key1, m.get(key2));
  m.put(key2, value);
}
ChssPly76
You could include a warning about this not being safe for multi-threaded operation.
Stephen Denne
@Stephen - according to OP, he ensured that values for both keys already exist; thus the above code does not modify the map structurally and is, therefore, safe (as in "won't break the Map"). It may, of course, yield unpredictable results if invoked for the same keys (e.g. (k1, k2) and (k1, k3)) and should be synchronized if that's the case.
ChssPly76
+2  A: 
m.put(key2, m.put(key1, m.get(key2))

...will work. put(..) returns the previous value for that key that was already in the map, which will then become associated with key2. You can do it without using a local variable; however this code is a little hard to understand, a variable might make the intent of your code clearer.

RMorrisey