gpt4 book ai didi

java - StringBuilder 比较返回错误结果

转载 作者:行者123 更新时间:2023-12-02 08:08:39 25 4
gpt4 key购买 nike

当我比较具有相同下划线字符串的两个 StringBuilder 对象时,即使值应该为 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));
}
}

最佳答案

这是因为 StringBuilder 不会覆盖 Object 类中的 equals 方法。

您必须将两个 StringBuilder 对象转换为 String,然后比较它们

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

这将为您提供正确的结果。显然,您必须介意null检查等。

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.

关于java - StringBuilder 比较返回错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47512361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com