0

So, I'm making a fullscreen application and ran across something weird.

The Method DisplayMode.equals(DisplayMode dm) is overridden but I don't think it's implemented quite right. The following code prints false to the console:

public static void main(String[] args){
    DisplayMode mode = new (1,2,16, DisplayMode.REFRESH_RATE_UNKNOWN);
    System.out.println(mode.equals(new DisplayMode(1, 2, 16, 60)));
}

If the display modes are the same save for their refresh rates, and one of them is unknown, then I think they should be equal. Why is that not the case, and can someone suggest a workaround for me to use? Also, why do the online the Java Docs show that there are two overloaded versions of the .equals() method, one with a DisplayMode Object and one with a Java.Lang.Object Object? https://docs.oracle.com/javase/7/docs/api/java/awt/DisplayMode.html

Avi Caspe
  • 537
  • 4
  • 12

1 Answers1

0

The difference I believe is that in the first case, you're saying "I know for a fact that the refresh rate is unknown" and in the second case you're saying "I know for a fact that the refresh rate is 60".

The implementation from grepcode shows the following:

public boolean equals(DisplayMode dm) {
    if (dm == null) {
        return false;
    }
    return (getHeight() == dm.getHeight()
         && getWidth() == dm.getWidth()
         && getBitDepth() == dm.getBitDepth()
         && getRefreshRate() == dm.getRefreshRate());
}

you can see that it compares the value of the refresh rate at the bottom.

java.awt.DisplayMode#REFRESH_RATE_UNKNOWN is defined as 0.

As for the second question, about why that overload the equals method, it allows the code to separated and focus on only the part it cares about. For example, if it were not overloaded, the equals method would look like

public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }

    if (obj instanceof DisplayMode) {
        DisplayMode dm = (DisplayMode) obj;

        return (getHeight() == dm.getHeight()
             && getWidth() == dm.getWidth()
             && getBitDepth() == dm.getBitDepth()
             && getRefreshRate() == dm.getRefreshRate());
    }

    return false;
}
Zymus
  • 1,673
  • 1
  • 18
  • 38
  • Why is there a .equals() method overridden for this object, but not the many dozens of other objects in the Java Libraries? – Avi Caspe May 18 '16 at 04:26
  • @AviCaspe I'm not certain of the answer. There may be a performance consideration to it. At compile time, the compiler is able to tell which exact method to call in this case; so if you wanted to compare two `DisplayMode` objects, you would save a couple of instructions by calling the one taking a `DisplayMode` as an argument, instead of the one taking an `Object`. Another thing to consider is that annotations didn't exist when this class was added, so you couldn't use `@Override` which may have something to do with it. – Zymus May 18 '16 at 06:18