Home > Back-end >  Java 11: Strange behaviour with Object.equals() method
Java 11: Strange behaviour with Object.equals() method

Time:11-17

I am working on some Java 11 test code that is moved over from Java 8. The code looks like this:

HttpsURLConnection urlc = setupURLConnection(url);
boolean eqs = urlc.equals(urlc);
assertFalse("Unexpected equals returned", eqs);

Looking at the Java 11 documentation, it mentions that any non-null reference object should return true when equals is called on itself. However, in Java 8 the above test passes the test, i.e. the above test determines urlc is not equal to itself in Java 8, while in Java 11 the test determines urlc is equal to itself. I can also confirm that the equals method is not overridden by anything, it is just the standard Object.equals method.

Which version of the test is correct and which is incorrect? Could it be possible that the test code is in fact right and there is some issue with the Java 11 code that is causing a test failure? Thanks for your help!

CodePudding user response:

Known bug

The Java 8 version is broken since it violates the contract for equals().

What you actually get when you create a HttpsURLConnection is a sun.net.www.protocol.https.HttpsURLConnectionImpl that has actually an equals() method:

public boolean equals(Object obj) {
    return delegate.equals(obj);
}

The delegate (usually a sun.net.www.protocol.https.DelegateHttpsURLConnection) in turn correctly implements equals() and therefore returns false, since the delegate itself is not an instance of HttpsURLConnectionImpl.

If your test depends on this broken behaviour then your test should be considered broken too.

See Issue # JDK-8055299, HttpsURLConnection.equals() broken. Bug exists in Java 7 and Java 8, fixed in Java 9 and later.

  • Related