简体   繁体   English

Java HashMap放入for循环中

[英]Java HashMap put in a for loop in

I have a for loop, where i check if there is a certain key in a HashMap, if the key is not there, it should put a new association in the HashMap. 我有一个for循环,在这里检查HashMap中是否存在某个键,如果该键不存在,则应在HashMap中放置一个新的关联。 The problem is that that it puts the association, but by the next iteration of the loop the association is gone! 问题在于,它放置了关联,但是在循环的下一次迭代中,关联消失了! I don't get it! 我不明白!

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);
    }
}

Arrays in Java don't provide an implementation of equals method. Java中的数组不提供equals方法的实现。 Eg, array1.equals(array2) will always be false , even if both arrays contain equal number of the same objects. 例如,即使两个数组包含相同数量的相同对象, array1.equals(array2)始终为false Therefore, you can't use them as map keys: map.containsKey won't work. 因此,您不能将它们用作地图键: map.containsKey将不起作用。

Try lists instead: Arrays.asList(1, 2) . 尝试使用列表: Arrays.asList(1, 2) Or create a special 'pair' object, since you only hold two elements in array. 或创建一个特殊的“对”对象,因为您仅在数组中包含两个元素。

As Nikita said, arrays don't implement an value-by-value equals. 正如Nikita所说,数组不会实现按值相等。 It's just an object equals. 这只是一个对象等于。

If you want to use this implementation you should use a Map with a custom comparator (like a TreeMap) and use for instance Arrays.equals in the implementation of that comparator. 如果要使用此实现,则应将Map与自定义比较器(如TreeMap)一起使用,并在该比较器的实现中使用实例Arrays.equals That way the elememts of colorCheck are also checked (array content), and not so much the array reference. 这样,也可以检查colorCheck的要素(数组内容),而不是数组引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM