简体   繁体   English

StringBuilder比较返回错误的结果

[英]StringBuilder comparison returns wrong result

When I compare two StringBuilder objects having same underline string, false is returned even when value should be true. 当我比较具有相同下划线字符串的两个StringBuilder对象时,即使value应该为true,也会返回false

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. 这是因为StringBuilder不会覆盖Object类中的equals方法。

You will have to convert both StringBuilder objects to String and then compare them 您必须将两个StringBuilder对象转换为String ,然后比较它们

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. 根据equals contract,如果equals被覆盖,则hashCode也必须被覆盖,但由于StringBuffer是可变的,因此其值的任何更改都将影响对象hashcode。 This might lead to stored values in HashMap to be lost if StringBuilder is used as keys. 如果将StringBuilder用作键,则可能导致HashMap存储值丢失。

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. 相反:转到javadoc首先确定该类是否重写 equals() - 如果是,请阅读其中的详细信息。

In other words: you simply assumed that StringBuilders are equal when they have matching content. 换句话说:您只是假设StringBuilders在匹配内容时是相同的 But that isn't true. 但事实并非如此。 Because this class doesn't override equals() you only receive a true result when doing someBuilder.equals(someBuilder) . 因为这个类不会覆盖equals() ,所以在执行someBuilder.equals(someBuilder)时只会收到一个true结果。 The chars sent into the builder simply do not matter when comparing builders. 在比较构建器时,发送到构建器的字符无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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