Created
January 10, 2017 21:31
-
-
Save 1cg/b56cc8faf048f317085cc2fa767f8b24 to your computer and use it in GitHub Desktop.
Helping understand different notions of equality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// gosu | |
var x = ... | |
var y = ... | |
if( x == y ) { | |
print("x and y are value equal, including null") | |
} | |
if( x === y ) { // note, triple equals! | |
print("x and y are references equal, including null") | |
} | |
if( x.equals( y ) ) { | |
print("x and y are value equal, unless x is null, in which case there is an NPE in the condition above.") | |
} | |
// java | |
Object x = ... | |
Object y = ... | |
if( x == y ) { | |
print("x and y are references equal, including null") | |
} | |
if( x.equals( y ) ) { | |
print("x and y are value equal, unless x is null, in which case there is an NPE in the condition above.") | |
} | |
// correct equality test in java | |
if( (x == y) || (x != null && x.equals(y)) ) { | |
print("x and y are value equal and this is null save") | |
} | |
// There is a helper for the above code: | |
if( java.util.Objects.equals(x, y) ) { | |
print("x and y are value equal and this is null save") | |
} | |
// now you can see why gosu is so much better than java... :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment