到目前为止,我一直在程序中使用==运算符来比较所有的字符串。 然而,我遇到了一个错误,将其中一个改为.equals(),它修复了这个错误。

==不好吗?什么时候应该使用,什么时候不应该使用?有什么不同?


当前回答

我认为当你定义一个字符串时,你就定义了一个对象。所以你需要使用。equals()。当你使用基本数据类型时,你可以使用==,但对于String(和任何对象),你必须使用.equals()。

其他回答

如果equals()方法出现在java.lang.Object类中,并且希望它检查对象状态的等价性!也就是说,对象的内容。而==运算符则用于检查实际的对象实例是否相同。

例子

考虑两个不同的参考变量str1和str2:

str1 = new String("abc");
str2 = new String("abc");

如果你使用equals()

System.out.println((str1.equals(str2))?"TRUE":"FALSE");

如果使用==,您将得到TRUE的输出。

System.out.println((str1==str2) ? "TRUE" : "FALSE");

现在您将得到FALSE作为输出,因为str1和str2都指向两个不同的对象,尽管它们共享相同的字符串内容。因为有了new String(),每次都会创建一个新对象。

功能:

public float simpleSimilarity(String u, String v) {
    String[] a = u.split(" ");
    String[] b = v.split(" ");

    long correct = 0;
    int minLen = Math.min(a.length, b.length);

    for (int i = 0; i < minLen; i++) {
        String aa = a[i];
        String bb = b[i];
        int minWordLength = Math.min(aa.length(), bb.length());

        for (int j = 0; j < minWordLength; j++) {
            if (aa.charAt(j) == bb.charAt(j)) {
                correct++;
            }
        }
    }

    return (float) (((double) correct) / Math.max(u.length(), v.length()));
}

测试:

String a = "This is the first string.";

String b = "this is not 1st string!";

// for exact string comparison, use .equals

boolean exact = a.equals(b);

// For similarity check, there are libraries for this
// Here I'll try a simple example I wrote

float similarity = simple_similarity(a,b);

==执行引用相等性检查,2个对象(在本例中为字符串)是否引用内存中的同一对象。

equals()方法检查两个对象的内容或状态是否相同。

显然==更快,但如果你只是想知道2个字符串是否包含相同的文本,在许多情况下会(可能)给出错误的结果。

当然推荐使用equals()方法。

不要担心性能。使用String.equals()有以下几点值得鼓励:

Implementation of String.equals() first checks for reference equality (using ==), and if the 2 strings are the same by reference, no further calculation is performed! If the 2 string references are not the same, String.equals() will next check the lengths of the strings. This is also a fast operation because the String class stores the length of the string, no need to count the characters or code points. If the lengths differ, no further check is performed, we know they cannot be equal. Only if we got this far will the contents of the 2 strings be actually compared, and this will be a short-hand comparison: not all the characters will be compared, if we find a mismatching character (at the same position in the 2 strings), no further characters will be checked.

当一切都说了,做了,即使我们可以保证字符串是实习生,使用equals()方法仍然不是人们可能认为的开销,绝对是推荐的方式。如果您想要有效的引用检查,那么在语言规范和实现保证相同enum值将是相同对象(通过引用)的地方使用enum。

==比较对象引用。

.equals()比较字符串值。

有时==会产生比较String值的错觉,如下所示:

String a="Test";
String b="Test";
if(a==b) ===> true

这是因为当您创建任何String字面值时,JVM首先在String池中搜索该字面值,如果找到匹配,则将相同的引用给予新的String。因此,我们得到:

(a==b) ==>为真

                       String Pool
     b -----------------> "test" <-----------------a

但是,==在以下情况下失效:

String a="test";
String b=new String("test");
if (a==b) ===> false

在这种情况下,对于new String("test"),语句new String将在堆上创建,并且该引用将被赋予给b,因此b将被赋予堆上的引用,而不是在String池中。

现在a指向String池中的String,而b指向堆中的String。因此我们得到:

如果(a==b) ==>假。

                String Pool
     "test" <-------------------- a

                   Heap
     "test" <-------------------- b

而.equals()总是比较String的值,所以在这两种情况下都是true:

String a="Test";
String b="Test";
if(a.equals(b)) ===> true

String a="test";
String b=new String("test");
if(a.equals(b)) ===> true

所以使用.equals()总是更好。

您还可以使用compareTo()方法来比较两个string。如果compareTo结果为0,则两个字符串相等,否则被比较的字符串不相等。

==比较引用,不比较实际字符串。如果你确实使用new string (somestring).intern()创建了每个字符串,那么你可以使用==操作符来比较两个字符串,否则只能使用equals()或compareTo方法。