到目前为止,我一直在程序中使用==运算符来比较所有的字符串。 然而,我遇到了一个错误,将其中一个改为.equals(),它修复了这个错误。
==不好吗?什么时候应该使用,什么时候不应该使用?有什么不同?
到目前为止,我一直在程序中使用==运算符来比较所有的字符串。 然而,我遇到了一个错误,将其中一个改为.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);
其他回答
==操作符检查两个字符串是否完全相同的对象。
equals()方法将检查两个字符串是否具有相同的值。
==测试对象引用,.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
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()。当你使用基本数据类型时,你可以使用==,但对于String(和任何对象),你必须使用.equals()。
我同意zacherates的回答。
但是你能做的是在非文字字符串上调用intern()。
来自zacherates的例子:
// ... but they are not the same object
new String("test") == "test" ==> false
如果你实习非文字字符串相等为真:
new String("test").intern() == "test" ==> true