Avi Caspe
Avi Caspe

Reputation: 575

DisplayMode.equals(DisplayMode dm) Confusion

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

Upvotes: 0

Views: 148

Answers (1)

Zymus
Zymus

Reputation: 1698

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

Upvotes: 0

Related Questions