What is the most efficient way to compare Strings
and to compare StringBuilders
?
cad1.equals(cad2);
cad1.compareTo(cad2);
After comparing any String/Builder
, should we hashCode
always do?
What is the most efficient way to compare Strings
and to compare StringBuilders
?
cad1.equals(cad2);
cad1.compareTo(cad2);
After comparing any String/Builder
, should we hashCode
always do?
Although I didn't quite understand what you're getting at, and although "efficiency" I doubt it matters in 99% of cases, it seems to
.equals()
be more efficient, plus it's clearer than.compareTo(another) == 0
and you avoid the hatefulNullPointerException
.Here you have the source.
http://www.docjar.com/html/api/java/lang/String.java.html
hasCode()
I don't know why you want to use it.And in case the differences are not clear to you,
StringBuilder
it is not immutable, unlikeString
. So it is advised to use it in cases where you want to morbidly modify stringsTo compare String objects you must use the equals method although you must be careful when comparing two StringBuilders with equals :
Calling the equals method of the StringBuilder class will return false even if the value of the string is the same because it does not override the equals() method of the Object class, so it will compare that both references point to the same object.
I hope it serves you Greetings.