简体   繁体   中英

StringBuilder comparison returns wrong result

When I compare two StringBuilder objects having same underline string, false is returned even when value should be true.

public class Test {

    public static void main(String [] args) {
        StringBuilder strBld_1 = new StringBuilder("string");
        StringBuilder strBld_2 = new StringBuilder("string");

        System.out.println(strBld_1.equals(strBld_2));
    }
 }

This is because StringBuilder doesn't override equals method from Object class.

You will have to convert both StringBuilder objects to String and then compare them

System.out.println(strBld_1.toString().equals(strBld_2.toString()));

This will give you correct result. Obviously, you will have to mind null checks etc.

As per equals contract, if equals is overriden then hashCode must also be overriden, but as StringBuffer is mutable so any change in its value will impact objects hashcode. This might lead to stored values in HashMap to be lost if StringBuilder is used as keys.

The deeper answer here: don't assume what equality means for a class. Instead: turn to the javadoc to first determine if that class overrides equals() - and if so, read about the details there.

In other words: you simply assumed that StringBuilders are equal when they have matching content. But that isn't true. Because this class doesn't override equals() you only receive a true result when doing someBuilder.equals(someBuilder) . The chars sent into the builder simply do not matter when comparing builders.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM