有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中比较两个字符串时出现奇怪的布尔答案

我遇到了一个奇怪的问题。我试图比较两个128位的字符串,我相信它们的每个字符都相互匹配(我测试了比较String.chartAt(#)好几次),但当我这样做时 如果(字符串1==字符串2) .. 其他的 .. 它转到了else条款。为什么呢


共 (1) 个答案

  1. # 1 楼答案

    使用==进行比较时,检查两个变量是否引用同一个对象(引用比较)。您应该使用strings equals()方法来比较它们是否在某种意义上是相等的,它们由相同的字符组成

    description of equals method in java documentation

    public boolean equals(Object anObject)

    Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.