到目前为止,我一直在程序中使用==运算符来比较所有的字符串。 然而,我遇到了一个错误,将其中一个改为.equals(),它修复了这个错误。
==不好吗?什么时候应该使用,什么时候不应该使用?有什么不同?
到目前为止,我一直在程序中使用==运算符来比较所有的字符串。 然而,我遇到了一个错误,将其中一个改为.equals(),它修复了这个错误。
==不好吗?什么时候应该使用,什么时候不应该使用?有什么不同?
当前回答
Java有一个String池,Java在该池下管理String对象的内存分配。参见Java中的字符串池
当您使用==操作符检查(比较)两个对象时,它将地址相等性比较到字符串池中。如果两个String对象具有相同的地址引用,则返回true,否则返回false。但是如果你想比较两个String对象的内容,那么你必须重写equals方法。
equals实际上是Object类的方法,但它被重写到String类中,并给出了一个比较Object内容的新定义。
Example:
stringObjectOne.equals(stringObjectTwo);
但注意,它尊重String的情况。如果你想要不区分大小写的比较,那么你必须使用String类的equalsIgnoreCase方法。
让我们来看看:
String one = "HELLO";
String two = "HELLO";
String three = new String("HELLO");
String four = "hello";
one == two; // TRUE
one == three; // FALSE
one == four; // FALSE
one.equals(two); // TRUE
one.equals(three); // TRUE
one.equals(four); // FALSE
one.equalsIgnoreCase(four); // 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);
所有对象都保证有一个.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.
是的,很糟糕……
==表示两个字符串引用是完全相同的对象。您可能听说过这种情况,因为Java保留了某种文字表(它确实如此),但情况并非总是如此。一些字符串以不同的方式加载,从其他字符串构造,等等,所以永远不要假设两个相同的字符串存储在相同的位置。
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(),每次都会创建一个新对象。
我认为当你定义一个字符串时,你就定义了一个对象。所以你需要使用。equals()。当你使用基本数据类型时,你可以使用==,但对于String(和任何对象),你必须使用.equals()。