[英]Java HashMap put in a for loop in
我有一個for循環,在這里檢查HashMap中是否存在某個鍵,如果該鍵不存在,則應在HashMap中放置一個新的關聯。 問題在於,它放置了關聯,但是在循環的下一次迭代中,關聯消失了! 我不明白!
public void DrawBoard(ArrayList<Integer[]> BoardList, int FrameX, int FrameY){
StdDraw.setCanvasSize(FrameX*50, FrameY*50);
StdDraw.clear(new Color(0,0,0));
StdDraw.setXscale(0, FrameX);
StdDraw.setYscale(FrameY, 0);
Map<Integer[], Color> Coloring = new HashMap<Integer[], Color>();
for(int i = 0; i < BoardList.size(); i++){
Integer[] Rectangle = BoardList.get(i);
Random rand = new Random();
Integer[] ColorCheck = {Rectangle[2], Rectangle[3]};
if(Coloring.containsKey(ColorCheck)){
StdDraw.setPenColor(Coloring.get(ColorCheck));}
else{
Color newColor = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
Coloring.put(ColorCheck, newColor);
StdDraw.setPenColor(newColor);
}
double x1 = Rectangle[0];
double y1 = Rectangle[1];
double x2 = Rectangle[2];
double y2 = Rectangle[3];
StdDraw.filledRectangle(x1+(x2/2), y1+(y2/2), x2/2, y2/2);
}
}
Java中的數組不提供equals
方法的實現。 例如,即使兩個數組包含相同數量的相同對象, array1.equals(array2)
始終為false
。 因此,您不能將它們用作地圖鍵: map.containsKey
將不起作用。
嘗試使用列表: Arrays.asList(1, 2)
。 或創建一個特殊的“對”對象,因為您僅在數組中包含兩個元素。
正如Nikita所說,數組不會實現按值相等。 這只是一個對象等於。
如果要使用此實現,則應將Map與自定義比較器(如TreeMap)一起使用,並在該比較器的實現中使用實例Arrays.equals 。 這樣,也可以檢查colorCheck的要素(數組內容),而不是數組引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.