我有一个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);
}
}
答案 0 :(得分:2)
Java中的数组不提供equals
方法的实现。例如,array1.equals(array2)
将始终为false
,即使两个数组包含相同数量的相同对象。因此,您不能将它们用作地图键:map.containsKey
将无效。
尝试使用列表:Arrays.asList(1, 2)
。或者创建一个特殊的“对”对象,因为你只在数组中包含两个元素。
答案 1 :(得分:2)
正如Nikita所说,数组没有实现按值等于。它只是一个对象等于。
如果要使用此实现,则应使用带有自定义比较器的Map(如TreeMap),并在该比较器的实现中使用实例Arrays.equals。这样, colorCheck 的元素也会被检查(数组内容),而不是数组引用。