Java在Map中交换两个键

2 java key map

欢迎.我有一个通用的void方法交换,它接受一个Map和2个键.该方法将交换与Map中的键相关联的值.我已经检查过两个键都包含在Map的其他地方,但在这个方法中,我不能使用循环.我的方法回答:

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?
}
Run Code Online (Sandbox Code Playgroud)

Chs*_*y76 9

使用临时持有人的价值:

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);
}
Run Code Online (Sandbox Code Playgroud)