Tuesday, October 30, 2018

java - How to compare two strings are equal in value, what is the best method?

You can either use the == operator or the Object.equals(Object) method.


The == operator checks whether the two subjects are the same object, whereas the equals method checks for equal contents (length and characters).


if(objectA == objectB) {
// objects are the same instance. i.e. compare two memory addresses against each other.
}
if(objectA.equals(objectB)) {
// objects have the same contents. i.e. compare all characters to each other
}

Which you choose depends on your logic - use == if you can and equals if you do not care about performance, it is quite fast anyhow.


String.intern() If you have two strings, you can internate them, i.e. make the JVM create a String pool and returning to you the instance equal to the pool instance (by calling String.intern()). This means that if you have two Strings, you can call String.intern() on both and then use the == operator. String.intern() is however expensive, and should only be used as an optimalization - it only pays off for multiple comparisons.


All in-code Strings are however already internated, so if you are not creating new Strings, you are free to use the == operator. In general, you are pretty safe (and fast) with


if(objectA == objectB || objectA.equals(objectB)) {
}

if you have a mix of the two scenarios. The inline


if(objectA == null ? objectB == null : objectA.equals(objectB)) {
}

can also be quite useful, it also handles null values since String.equals(..) checks for null.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...