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

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


当前回答

所有对象都保证有一个.equals()方法,因为Object包含一个返回布尔值的方法。equals()。如果需要进一步的定义,子类的工作就是重写这个方法。如果没有它(即使用==),则只检查两个对象之间的内存地址是否相等。String重写了这个.equals()方法,它没有使用内存地址,而是返回字符级别的字符串的相等性比较。

A key note is that strings are stored in one lump pool so once a string is created it is forever stored in a program at the same address. Strings do not change, they are immutable. This is why it is a bad idea to use regular string concatenation if you have a serious of amount of string processing to do. Instead you would use the StringBuilder classes provided. Remember the pointers to this string can change and if you were interested to see if two pointers were the same == would be a fine way to go. Strings themselves do not.

其他回答

==测试对象引用,.equals()测试字符串值。

有时,==看起来像是比较值,因为Java在幕后做了一些工作,以确保相同的内联字符串实际上是相同的对象。

例如:

String fooString1 = new String("foo");
String fooString2 = new String("foo");

// Evaluates to false
fooString1 == fooString2;

// Evaluates to true
fooString1.equals(fooString2);

// Evaluates to true, because Java uses the same object
"bar" == "bar";

但是要小心空值!

==可以处理空字符串,但从空字符串调用.equals()会导致异常:

String nullString1 = null;
String nullString2 = null;

// Evaluates to true
System.out.print(nullString1 == nullString2);

// Throws a NullPointerException
System.out.print(nullString1.equals(nullString2));

因此,如果您知道fooString1可能为空,请通过写入来告诉读取器

System.out.print(fooString1 != null && fooString1.equals("bar"));

下面是更短的,但不太明显,它检查null:

System.out.print("bar".equals(fooString1));  // "bar" is never null
System.out.print(Objects.equals(fooString1, "bar"));  // Java 7 required

==比较对象引用。

.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()总是更好。

操作符==总是用于对象引用比较,而String类.equals()方法用于内容比较被重写:

String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2); // It prints false (reference comparison)
System.out.println(s1.equals(s2)); // It prints true (content comparison)

是的,==不利于比较字符串(实际上是任何对象,除非您知道它们是规范的)。==只是比较对象引用。.equals()测试是否相等。对于字符串,它们通常是相同的,但正如你所发现的,这并不总是保证的。

功能:

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