Timeline for Compare two objects in Java with possible null values
Current License: CC BY-SA 3.0
11 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
May 25, 2020 at 10:20 | comment | added | Holger |
@hyperpallium the first thing, String.equals does internally, is a reference comparison, like if(this == other) return true; . Since String is final , even the simplest JVMs will be capable of inlining that code, not to speak of modern common implementations. So if the strings are identical (equal and interned), the early reference comparison doesn’t gain much and in all other cases, it doesn’t help at all, except for the scenario where both are null , perhaps.
|
|
Jun 25, 2019 at 9:10 | comment | added | hyperpallium | This is the clearest implementation, but the answer added to the question checks reference equality first, so is faster (if many strings are interned), even though it has worst-case three comparisons. I choose clarity! | |
Jan 9, 2018 at 20:14 | comment | added | Cat | @LonelyNeuron That only applies to Java 7+. | |
Jan 9, 2018 at 20:13 | comment | added | Neuron |
i suggest using Objects.equals(Object, Object) as Mark Rotteveel has pointed out in his answer (please upvote it)
|
|
Dec 15, 2016 at 23:24 | comment | added | coya |
Hey! you shouldn't have a compare method returning true/false. Equals is not the same as compare. Compare should be useful for sorting. You should return <0 , ==0 or >0 to indicate which one is lower/grater than the other
|
|
Jul 28, 2014 at 4:59 | comment | added | Cat |
@VolodymyrLevytskyi This particular compare method is not in the Java JDK. If it was, I would suggest using that.
|
|
Jul 25, 2014 at 13:58 | comment | added | Volodymyr Levytskyi | Which java class contains method you provided? | |
Nov 7, 2013 at 18:31 | comment | added | Tom | Why not just change the String types to Objects - making it more generic? And then it is the same as what you will get if you move to Java 7. | |
Jul 26, 2013 at 15:47 | history | edited | Cat | CC BY-SA 3.0 |
added 7 characters in body
|
Jun 30, 2012 at 13:51 | vote | accept | priceline | ||
Jun 30, 2012 at 5:11 | history | answered | Cat | CC BY-SA 3.0 |