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

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


当前回答

==比较Java中的对象引用,String对象也不例外。

为了比较对象(包括String)的实际内容,必须使用equals方法。

如果使用==对两个String对象进行比较的结果为真,那是因为String对象被合并了,并且Java虚拟机有多个引用指向同一个String实例。不要期望使用==比较一个包含相同内容的String对象与另一个String对象的计算结果为true。

其他回答

==比较Java中的对象引用,String对象也不例外。

为了比较对象(包括String)的实际内容,必须使用equals方法。

如果使用==对两个String对象进行比较的结果为真,那是因为String对象被合并了,并且Java虚拟机有多个引用指向同一个String实例。不要期望使用==比较一个包含相同内容的String对象与另一个String对象的计算结果为true。

String a = new String("foo");
String b = new String("foo");
System.out.println(a == b); // prints false
System.out.println(a.equals(b)); // prints true

确保你明白其中的原因。这是因为==比较只比较引用;equals()方法对内容逐字符进行比较。

当你为a和b调用new时,每一个都得到一个指向字符串表中的“foo”的新引用。参考文献不同,但内容是一样的。

==操作符检查两个引用是否指向同一个对象。.equals()检查实际的字符串内容(值)。

注意.equals()方法属于类Object(所有类的超类)。您需要根据您的类需求重写它,但是对于String,它已经实现了,并且它检查两个字符串是否具有相同的值。

Case 1 String s1 = "Stack Overflow"; String s2 = "Stack Overflow"; s1 == s2; //true s1.equals(s2); //true Reason: String literals created without null are stored in the String pool in the permgen area of heap. So both s1 and s2 point to same object in the pool. Case 2 String s1 = new String("Stack Overflow"); String s2 = new String("Stack Overflow"); s1 == s2; //false s1.equals(s2); //true Reason: If you create a String object using the new keyword a separate space is allocated to it on the heap.

.equals()比较类中的数据(假设函数已经实现)。 ==比较指针位置(对象在内存中的位置)。

==如果两个对象(不是谈论原语)指向同一个对象实例,则返回true。 .equals()如果两个对象包含相同的数据,则返回true

那可能对你有帮助。

功能:

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);