我現在正在玩hashmaps。我試圖弄清楚如何比較兩個hashmaps的值 - 當每個hashmap的值是一個char數組。我環顧四周發現了一些可能有用的方法 - 我只是不確定如何正確實施。基本上我有兩個具有不同鍵的地圖,但具有相同的值。我想遍歷其中一個映射並創建一個布爾值,如果它們具有相同的值,則返回true。如果有人能幫我弄清楚,那就太好了。我的代碼如下什麼我迄今爲止嘗試:將char數組作爲值進行比較 - Java
publipublic class MapExample {
public static void main(String[] args) {
Map<String, char[]> map1 = new HashMap<String, char[]>();
Map<String, char[]> map2 = new HashMap<String, char[]>();
char[] letters1 = new char[3];
letters1[0] = 'a';
letters1[1] = 'b';
letters1[2] = 'c';
char[] letters2 = new char[3];
letters2[0] = 'x';
letters2[1] = 'y';
letters2[2] = 'z';
map1.put("1", letters1);
map1.put("2", letters2);
map1.put("3", letters1);
map2.put("4", letters1);
Set s = map1.entrySet();
Iterator it = s.iterator();
boolean containsValue;
//I've tried this but it produces false (and infinite loop) when maps have the same value
while (it.hasNext()) {
containsValue = map1.equals(map2.values());
System.out.println(containsValue);
}
//I've tried this too, but can't seem to adjust the lists to accept char[]
/*
List<String> values1 = new ArrayList<String>(map1.values());
List<String> values2 = new ArrayList<String>(map2.values());
Collections.sort(values1);
Collections.sort(values2);
boolean mapsHaveEqualValues = values1.equals(values2);*/
}
}
你的無限循環是因爲你沒有推進迭代器。你需要在某個時候調用'it.next()'。 – pamphlet