Take the 2-minute tour ×

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. 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]};
        Color newColor = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
        Coloring.put(ColorCheck, 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);
share|improve this question
Just for the record, in Java variables / members are usually lowercased. You have a .Net background? –  extraneon Oct 30 '10 at 16:54
I have no background, this is one of my first assignments at my University. Hence the slightly messy etiquette. –  Lauge Oct 30 '10 at 18:12

2 Answers 2

up vote 2 down vote accepted

As Nikita said, arrays don't implement an value-by-value equals. 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. That way the elememts of colorCheck are also checked (array content), and not so much the array reference.

share|improve this answer
Thanks a million, I just used an ArrayList instead. –  Lauge Oct 30 '10 at 18:11

Arrays in Java don't provide an implementation of equals method. E.g., array1.equals(array2) will always be false, even if both arrays contain equal number of the same objects. Therefore, you can't use them as map keys: map.containsKey won't work.

Try lists instead: Arrays.asList(1, 2). Or create a special 'pair' object, since you only hold two elements in array.

share|improve this answer

Your Answer


