2

I have a getPixelColour function:

Color getPixelColor(int x, int y) {
    if(mazeImage == null) System.out.println(":(");
    int pixel = mazeImage.getRGB(x, y);
    int  red = (pixel & 0x00ff0000) >> 16;
    int  green = (pixel & 0x0000ff00) >> 8;
    int  blue = pixel & 0x000000ff;
    return new Color(red,green,blue);
}

For example a pixel is black, and System.out.println(getPixelColor(x,y) + " " + Color.BLACK); writes java.awt.Color[r=0,g=0,b=0] java.awt.Color[r=0,g=0,b=0]

But getPixelColor(x,y) == Color.BLACK returns false. What's wrong with it?

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
DarkSun
  • 451
  • 1
  • 7
  • 19
  • If you found any of the below answers helpful you should accept one. As you post more questions members will be reluctant to help you unless you accept useful answers. – darrengorman Apr 07 '12 at 13:26

4 Answers4

4

You are comparing two different Color objects which will return false (i.e., two different objects at different memory locations).

If you wish to properly compare them, use equals():

getPixelColor(x, y).equals(Color.BLACK);
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
4

Instead of using getPixelColor(x, y) == Color.BLACK try Color.BLACK.equals(getPixelColor(x, y))

You should also read up on the equals method in Java and when it is appropriate to use it vs. the == operator.

darrengorman
  • 12,952
  • 2
  • 23
  • 24
2

If you do

getPixelColor(x,y).equals(Color.BLACK);

I'm sure you will get the result you expect.

The == operator in java is reference equality, and since getPixelColor() returns a new instance of Color it'll never == to Color.BLACK as this a static reference to another instance that happens to be the colour black.

Gareth Davis
  • 27,701
  • 12
  • 73
  • 106
2

Color is an object and == compares not the contents of the objects but the instances. So there can be several Color objects containing the RGB values (0,0,0).

You want to compare with col1.equals(col2).

You might look around this site and find plenty of other questions regaring == and equals. As an example:

Java String.equals versus ==

Community
  • 1
  • 1
A.H.
  • 63,967
  • 15
  • 92
  • 126