我如何比较Java中的字符串?

时间:2022-04-29 07:11:55

I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.

我在程序中使用==操作符来比较所有字符串。但是,我遇到了一个错误,将其中一个更改为.equals(),并修复了错误。

Is == bad? When should it and should it not be used? What's the difference?

= =是坏事?什么时候应该使用,什么时候不应该使用?有什么区别呢?

23 个解决方案

#1


4750  

== tests for reference equality (whether they are the same object).

==检验是否相等(是否相同)。

.equals() tests for value equality (whether they are logically "equal").

.equals()测试值相等(是否逻辑上“相等”)。

Objects.equals() checks for nulls before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Objects.equals()在调用.equals()之前检查是否为null,因此您不必(也可以使用在Guava中可用的JDK7)。

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

因此,如果您想测试两个字符串是否具有相同的值,您可能需要使用Objects.equals()。

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true 

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false

You almost always want to useObjects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.

您几乎总是想使用objects.equals()。在极少数情况下,你知道你在处理的是内嵌的字符串,你可以使用==。

From JLS 3.10.5. String Literals:

JLS 3.10.5。字符串:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

此外,字符串文本总是引用类字符串的相同实例。这是因为字符串——或者更一般来说,字符串常量表达式的值(§15.28)——“实习”,分享独特的实例,使用方法String.intern。

Similar examples can also be found in JLS 3.10.5-1.

在JLS 3.10.5-1中也可以找到类似的例子。

#2


594  

== tests object references, .equals() tests the string values.

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

Sometimes it looks as if == compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.

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

For example:

例如:

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

But beware of nulls!

但要注意取消!

== handles null strings fine, but calling .equals() from a null string will cause an exception:

==处理null字符串,但是从空字符串调用.equals()将导致异常:

String nullString1 = null;
String nullString2 = null;

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

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

#3


383  

== compares Object references.

= =比较对象引用。

.equals() compares String values.

.equals()比较字符串值。

Sometimes == gives illusions of comparing String values, as in following cases:

有时==会产生比较字符串值的错觉,如下列情况:

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

This is because when you create any String literal, the JVM first searches for that literal in the String pool, and if it finds a match, that same reference will be given to the new String. Because of this, we get:

这是因为当您创建任何字符串文字时,JVM首先在字符串池中搜索该文本,如果它找到匹配,那么将对新字符串提供相同的引用。因此,我们得到:

(a==b) ===> true

(= = b)= = = > true

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

However, == fails in the following case:

但是,==在下列情况下失败:

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

In this case for new String("test") the statement new String will be created on the heap, and that reference will be given to b, so b will be given a reference on the heap, not in String pool.

在这种情况下,对于新字符串(“test”),将在堆上创建语句新字符串,并将该引用赋给b,因此b将在堆中获得引用,而不是在字符串池中。

Now a is pointing to a String in the String pool while b is pointing to a String on the heap. Because of that we get:

现在a指向字符串池中的字符串,而b指向堆上的字符串。因为我们得到了:

if(a==b) ===> false.

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

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

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

While .equals() always compares a value of String so it gives true in both cases:

While .equals()总是比较字符串的值,所以在这两种情况下都是正确的:

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

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

So using .equals() is always better.

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

#4


196  

The == operator checks to see if the two strings are exactly the same object.

操作符检查两个字符串是否完全相同。

The .equals() method will check if the two strings have the same value.

.equals()方法将检查这两个字符串是否具有相同的值。

#5


147  

Strings in Java are immutable. That means whenever you try to change/modify the string you get a new instance. You cannot change the original string. This has been done so that these string instances can be cached. A typical program contains a lot of string references and caching these instances can decrease the memory footprint and increase the performance of the program.

Java中的字符串是不可变的。这意味着每当您尝试更改/修改字符串时,您将获得一个新实例。不能更改原始字符串。这样就可以缓存这些字符串实例。一个典型的程序包含大量的字符串引用,缓存这些实例可以减少内存占用,并提高程序的性能。

When using == operator for string comparison you are not comparing the contents of the string, but are actually comparing the memory address. If they are both equal it will return true and false otherwise. Whereas equals in string compares the string contents.

当使用==操作符进行字符串比较时,您并没有比较字符串的内容,而是比较了内存地址。如果它们都相等,它将返回真和假。而在字符串中等于字符串的内容。

So the question is if all the strings are cached in the system, how come == returns false whereas equals return true? Well, this is possible. If you make a new string like String str = new String("Testing") you end up creating a new string in the cache even if the cache already contains a string having the same content. In short "MyString" == new String("MyString") will always return false.

问题是,如果所有的字符串都缓存在系统中,为什么==返回false,而等于返回true?嗯,这是可能的。如果您创建了一个新的字符串,比如string str = new string(“test”),那么即使缓存已经包含了具有相同内容的字符串,也会在缓存中创建一个新字符串。简言之,“MyString”== new String(“MyString”)将始终返回false。

Java also talks about the function intern() that can be used on a string to make it part of the cache so "MyString" == new String("MyString").intern() will return true.

Java还讨论了可以在字符串中使用的函数intern(),从而使它成为缓存的一部分,因此“MyString”== new string(“MyString”).intern()将返回true。

Note: == operator is much faster than equals just because you are comparing two memory addresses, but you need to be sure that the code isn't creating new String instances in the code. Otherwise you will encounter bugs.

注意:==操作符的速度要快得多,因为您正在比较两个内存地址,但是您需要确保代码不会在代码中创建新的字符串实例。否则就会遇到错误。

#6


124  

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

Make sure you understand why. It's because the == comparison only compares references; the equals() method does a character-by-character comparison of the contents.

一定要弄明白为什么。因为==比较只比较引用;equals()方法对内容进行逐个字符的比较。

When you call new for a and b, each one gets a new reference that points to the "foo" in the string table. The references are different, but the content is the same.

当您调用new for a和b时,每一个都得到一个新的引用,指向字符串表中的“foo”。引用是不同的,但是内容是相同的。

#7


109  

Yea, it's bad...

是的,很糟糕……

== means that your two string references are exactly the same object. You may have heard that this is the case because Java keeps sort of a literal table (which it does), but that is not always the case. Some strings are loaded in different ways, constructed from other strings, etc., so you must never assume that two identical strings are stored in the same location.

==表示您的两个字符串引用是完全相同的对象。您可能听说过这种情况,因为Java保持了一种文字表(确实如此),但情况并非总是如此。有些字符串以不同的方式加载,由其他字符串组成,等等,所以您不能假设两个相同的字符串存储在同一个位置。

Equals does the real comparison for you.

和你真正的比较。

#8


104  

Yes, == is bad for comparing Strings (any objects really, unless you know they're canonical). == just compares object references. .equals() tests for equality. For Strings, often they'll be the same but as you've discovered, that's not guaranteed always.

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

#9


101  

Java have a String pool under which Java manages the memory allocation for the String objects. See String Pools in Java

Java有一个字符串池,其中Java管理字符串对象的内存分配。参见Java中的字符串池。

When you check (compare) two objects using the == operator it compares the address equality into the string-pool. If the two String objects have the same address references then it returns true, otherwise false. But if you want to compare the contents of two String objects then you must override the equals method.

当您使用==操作符检查(比较)两个对象时,它将地址平等与字符串池进行比较。如果两个字符串对象具有相同的地址引用,则返回true,否则为false。但是如果要比较两个字符串对象的内容,那么必须重写equals方法。

equals is actually the method of the Object class, but it is Overridden into the String class and a new definition is given which compares the contents of object.

equals实际上是对象类的方法,但是它被覆盖到String类中,并且给出了一个新的定义,用来比较对象的内容。

Example:
    stringObjectOne.equals(stringObjectTwo);

But mind it respects the case of String. If you want case insensitive compare then you must go for the equalsIgnoreCase method of the String class.

但请注意,它尊重字符串的情况。如果您想要区分大小写,那么您必须使用String类的equalsIgnoreCase方法。

Let's See:

让我们来看看:

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

#10


89  

.equals() compares the data in a class (assuming the function is implemented). == compares pointer locations (location of the object in memory).

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

== returns true if both objects (NOT TALKING ABOUT PRIMITIVES) point to the SAME object instance. .equals() returns true if the two objects contain the same data equals() Versus == in Java

==返回true,如果两个对象(不讨论原语)指向相同的对象实例。. =()返回true,如果两个对象包含相同的数据=()和==在Java中。

That may help you.

这可能会帮助你。

#11


88  

== compares object references in Java, and that is no exception for String objects.

==在Java中比较对象引用,对于字符串对象也不例外。

For comparing the actual contents of objects (including String), one must use the equals method.

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

If a comparison of two String objects using == turns out to be true, that is because the String objects were interned, and the Java Virtual Machine is having multiple references point to the same instance of String. One should not expect that comparing one String object containing the same contents as another String object using == to evaluate as true.

如果使用==的两个字符串对象的比较是正确的,那是因为字符串对象被interned,而Java虚拟机有多个引用指向同一个字符串实例。我们不应该期望将包含相同内容的一个字符串对象与另一个字符串对象进行比较。

#12


85  

== performs a reference equality check, whether the 2 objects (strings in this case) refer to the same object in the memory.

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

The equals() method will check whether the contents or the states of 2 objects are the same.

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

Obviously == is faster, but will (might) give false results in many cases if you just want to tell if 2 Strings hold the same text.

显然==更快,但在很多情况下(可能)会给出错误的结果,如果您只是想判断两个字符串是否具有相同的文本。

Definitely the use of equals() method is recommended.

建议使用equals()方法。

Don't worry about the performance. Some things to encourage using String.equals():

不要担心表演。一些鼓励使用String.equals():

  1. 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!
  2. 执行String.equals()第一次检查引用的相等(使用==),如果两个字符串是相同的,则没有进行进一步的计算!
  3. 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.
  4. 如果两个字符串引用不相同,string .equals()将会检查字符串的长度。这也是一个快速操作,因为String类存储字符串的长度,不需要计算字符或代码点。如果长度不同,则不进行进一步检查,我们知道它们不可能相等。
  5. 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.
  6. 只有当我们得到这两个字符串的内容时,才会比较两个字符串的内容,这将是一个简短的比较:不是所有的字符都将被比较,如果我们发现一个不匹配的字符(在两个字符串中相同的位置),就不会检查更多的字符。

When all is said and done, even if we have guarantee that the strings are interns, using the equals() method is still not that overhead that one might think, definitely the recommended way. If you want efficient reference check, then use enums where it is guaranteed by the language specification and implementation that the same enum value will be the same object (by reference).

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

#13


83  

I agree with the answer from zacherates.

我同意zacherates的回答。

But what you can do is to call intern() on your non-literal strings.

但是你能做的是在你的非文字字符串上调用实习生()。

From zacherates example:

从zacherates例子:

// ... but they are not the same object
new String("test") == "test" ==> false 

If you intern the non-literal String equality is true

如果你实习,非文字的字符串等式是正确的。

new String("test").intern() == "test" ==> true 

#14


75  

If you're like me, when I first started using Java, I wanted to use the "==" operator to test whether two String instances were equal, but for better or worse, that's not the correct way to do it in Java.

如果您像我一样,当我第一次使用Java时,我想使用“==”操作符来测试两个字符串实例是否相等,但是无论好坏,这不是用Java实现的正确方法。

In this tutorial I'll demonstrate several different ways to correctly compare Java strings, starting with the approach I use most of the time. At the end of this Java String comparison tutorial I'll also discuss why the "==" operator doesn't work when comparing Java strings.

在本教程中,我将演示几种不同的方法来正确地比较Java字符串,从我大部分时间使用的方法开始。在这个Java字符串比较教程的最后,我还将讨论为什么“==”操作符在比较Java字符串时不起作用。

Option 1: Java String comparison with the equals method Most of the time (maybe 95% of the time) I compare strings with the equals method of the Java String class, like this:

选项1:Java字符串与equals方法的比较(大约95%的时间),我将字符串与Java String类的equals方法进行比较,如下所示:

if (string1.equals(string2))

This String equals method looks at the two Java strings, and if they contain the exact same string of characters, they are considered equal.

此字符串equals方法查看两个Java字符串,如果它们包含完全相同的字符串,则认为它们是相等的。

Taking a look at a quick String comparison example with the equals method, if the following test were run, the two strings would not be considered equal because the characters are not the exactly the same (the case of the characters is different):

如果使用equals方法查看一个快速的字符串比较示例,如果运行以下测试,那么两个字符串将不会被认为是相等的,因为字符不是完全相同的(字符的情况不同):

String string1 = "foo";
String string2 = "FOO";

if (string1.equals(string2))
{
    // this line will not print because the
    // java string equals method returns false:
    System.out.println("The two strings are the same.")
}

But, when the two strings contain the exact same string of characters, the equals method will return true, as in this example:

但是,当两个字符串包含完全相同的字符串时,equals方法将返回true,就像在这个例子中那样:

String string1 = "foo";
String string2 = "foo";

// test for equality with the java string equals method
if (string1.equals(string2))
{
    // this line WILL print
    System.out.println("The two strings are the same.")
}

Option 2: String comparison with the equalsIgnoreCase method

选项2:与equalsIgnoreCase方法的字符串比较。

In some string comparison tests you'll want to ignore whether the strings are uppercase or lowercase. When you want to test your strings for equality in this case-insensitive manner, use the equalsIgnoreCase method of the String class, like this:

在一些字符串比较测试中,您需要忽略字符串是大写还是小写。当您想以这种不区分大小写的方式测试您的字符串时,请使用String类的equalsIgnoreCase方法,如下所示:

String string1 = "foo";
String string2 = "FOO";

 // java string compare while ignoring case
 if (string1.equalsIgnoreCase(string2))
 {
     // this line WILL print
     System.out.println("Ignoring case, the two strings are the same.")
 }

Option 3: Java String comparison with the compareTo method

选项3:Java字符串与compareTo方法的比较。

There is also a third, less common way to compare Java strings, and that's with the String class compareTo method. If the two strings are exactly the same, the compareTo method will return a value of 0 (zero). Here's a quick example of what this String comparison approach looks like:

还有第三种比较少见的比较Java字符串的方法,这是使用String类compareTo方法。如果这两个字符串完全相同,那么compareTo方法将返回一个0(0)的值。下面是这个字符串比较方法的一个简单示例:

String string1 = "foo bar";
String string2 = "foo bar";

// java string compare example
if (string1.compareTo(string2) == 0)
{
    // this line WILL print
    System.out.println("The two strings are the same.")
}

While I'm writing about this concept of equality in Java, it's important to note that the Java language includes an equals method in the base Java Object class. Whenever you're creating your own objects and you want to provide a means to see if two instances of your object are "equal", you should override (and implement) this equals method in your class (in the same way the Java language provides this equality/comparison behavior in the String equals method).

虽然我在写Java中关于平等的概念,但需要注意的是,Java语言中包含了基本Java对象类中的equals方法。当您创建自己的对象时,您希望提供一种方法来查看您的对象的两个实例是否“相等”,您应该在类中重写(并实现)这个equals方法(就像Java语言在String equals方法中提供这种相等/比较行为一样)。

You may want to have a look at this ==, .equals(), compareTo(), and compare()

您可能需要查看这个==,.equals(), compareTo(),并比较()

#15


71  

Function:

功能:

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

Test:

测试:

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

#16


63  

The == operator check if the two references point to the same object or not. .equals() check for the actual string content (value).

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

Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented, and it checks whether two strings have the same value or not.

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

  • Case 1

    案例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.

    原因:在堆的permgen区域中,在字符串池中存储了没有null的字符串。所以s1和s2指向池中相同的对象。

  • Case 2

    案例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.

    原因:如果您使用new关键字创建一个字符串对象,则在堆上分配一个单独的空间。

#17


47  

== compares the reference value of objects whereas the equals() method present in the java.lang.String class compares the contents of the String object (to another object).

==比较对象的引用值,而在java.lang中显示equals()方法。String类比较字符串对象(指向另一个对象)的内容。

#18


45  

I think that when you define a String you define an object. So you need to use .equals(). When you use primitive data types you use == but with String (and any object) you must use .equals().

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

#19


38  

If the equals() method is present in the java.lang.Object class, and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the == operator is expected to check the actual object instances are same or not.

如果equals()方法存在于java.lang中。对象类,它将检查对象状态的等价性!也就是说,对象的内容。而==操作符将检查实际对象实例是否相同。

Example

例子

Consider two different reference variables, str1 and str2:

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

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

If you use the equals()

如果使用equals()

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

You will get the output as TRUE if you use ==.

如果使用==,则输出为TRUE。

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

Now you will get the FALSE as output, because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() a new object is created every time.

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

#20


36  

Operator == is always meant for object reference comparison, whereas the String class .equals() method is overridden for content comparison:

操作符==总是用于对象引用比较,而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)

#21


32  

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.

在Java中,当“==”操作符用于比较两个对象时,它会检查对象是否在内存中引用相同的位置。换句话说,它检查两个对象名称是否基本引用相同的内存位置。

The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

Java String类实际上覆盖了对象类中的默认equals()实现——它重写了方法,使它只检查字符串的值,而不是检查它们在内存中的位置。这意味着如果您调用equals()方法来比较两个字符串对象,那么只要字符的实际序列是相等的,那么这两个对象都是相等的。

The == operator checks if the two strings are exactly the same object.

操作符检查两个字符串是否完全相同。

The .equals() method check if the two strings have the same value.

方法检查两个字符串是否具有相同的值。

#22


32  

All objects are guaranteed to have a .equals() method since Object contains a method, .equals(), that returns a boolean. It is the subclass' job to override this method if a further defining definition is required. Without it (i.e. using ==) only memory addresses are checked between two objects for equality. String overrides this .equals() method and instead of using the memory address it returns the comparison of strings at the character level for equality.

所有对象都保证有一个.equals()方法,因为对象包含一个方法,.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.

一个关键的说明是字符串存储在一个块池中,因此一旦字符串被创建,它就会永远存储在同一个地址的程序中。字符串不会改变,它们是不可变的。这就是为什么如果您要处理大量的字符串处理,那么使用常规字符串连接是一个坏主意。相反,您将使用提供的StringBuilder类。记住,这个字符串的指针可以改变,如果你有兴趣看看两个指针是否相同==将是一个很好的方法。字符串本身不需要。

#23


32  

You can also use the compareTo() method to compare two Strings. If the compareTo result is 0, then the two strings are equal, otherwise the strings being compared are not equal.

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

The == compares the references and does not compare the actual strings. If you did create every string using new String(somestring).intern() then you can use the == operator to compare two strings, otherwise equals() or compareTo methods can only be used.

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

#1


4750  

== tests for reference equality (whether they are the same object).

==检验是否相等(是否相同)。

.equals() tests for value equality (whether they are logically "equal").

.equals()测试值相等(是否逻辑上“相等”)。

Objects.equals() checks for nulls before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Objects.equals()在调用.equals()之前检查是否为null,因此您不必(也可以使用在Guava中可用的JDK7)。

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

因此,如果您想测试两个字符串是否具有相同的值,您可能需要使用Objects.equals()。

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true 

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false

You almost always want to useObjects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.

您几乎总是想使用objects.equals()。在极少数情况下,你知道你在处理的是内嵌的字符串,你可以使用==。

From JLS 3.10.5. String Literals:

JLS 3.10.5。字符串:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

此外,字符串文本总是引用类字符串的相同实例。这是因为字符串——或者更一般来说,字符串常量表达式的值(§15.28)——“实习”,分享独特的实例,使用方法String.intern。

Similar examples can also be found in JLS 3.10.5-1.

在JLS 3.10.5-1中也可以找到类似的例子。

#2


594  

== tests object references, .equals() tests the string values.

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

Sometimes it looks as if == compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.

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

For example:

例如:

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

But beware of nulls!

但要注意取消!

== handles null strings fine, but calling .equals() from a null string will cause an exception:

==处理null字符串,但是从空字符串调用.equals()将导致异常:

String nullString1 = null;
String nullString2 = null;

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

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

#3


383  

== compares Object references.

= =比较对象引用。

.equals() compares String values.

.equals()比较字符串值。

Sometimes == gives illusions of comparing String values, as in following cases:

有时==会产生比较字符串值的错觉,如下列情况:

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

This is because when you create any String literal, the JVM first searches for that literal in the String pool, and if it finds a match, that same reference will be given to the new String. Because of this, we get:

这是因为当您创建任何字符串文字时,JVM首先在字符串池中搜索该文本,如果它找到匹配,那么将对新字符串提供相同的引用。因此,我们得到:

(a==b) ===> true

(= = b)= = = > true

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

However, == fails in the following case:

但是,==在下列情况下失败:

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

In this case for new String("test") the statement new String will be created on the heap, and that reference will be given to b, so b will be given a reference on the heap, not in String pool.

在这种情况下,对于新字符串(“test”),将在堆上创建语句新字符串,并将该引用赋给b,因此b将在堆中获得引用,而不是在字符串池中。

Now a is pointing to a String in the String pool while b is pointing to a String on the heap. Because of that we get:

现在a指向字符串池中的字符串,而b指向堆上的字符串。因为我们得到了:

if(a==b) ===> false.

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

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

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

While .equals() always compares a value of String so it gives true in both cases:

While .equals()总是比较字符串的值,所以在这两种情况下都是正确的:

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

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

So using .equals() is always better.

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

#4


196  

The == operator checks to see if the two strings are exactly the same object.

操作符检查两个字符串是否完全相同。

The .equals() method will check if the two strings have the same value.

.equals()方法将检查这两个字符串是否具有相同的值。

#5


147  

Strings in Java are immutable. That means whenever you try to change/modify the string you get a new instance. You cannot change the original string. This has been done so that these string instances can be cached. A typical program contains a lot of string references and caching these instances can decrease the memory footprint and increase the performance of the program.

Java中的字符串是不可变的。这意味着每当您尝试更改/修改字符串时,您将获得一个新实例。不能更改原始字符串。这样就可以缓存这些字符串实例。一个典型的程序包含大量的字符串引用,缓存这些实例可以减少内存占用,并提高程序的性能。

When using == operator for string comparison you are not comparing the contents of the string, but are actually comparing the memory address. If they are both equal it will return true and false otherwise. Whereas equals in string compares the string contents.

当使用==操作符进行字符串比较时,您并没有比较字符串的内容,而是比较了内存地址。如果它们都相等,它将返回真和假。而在字符串中等于字符串的内容。

So the question is if all the strings are cached in the system, how come == returns false whereas equals return true? Well, this is possible. If you make a new string like String str = new String("Testing") you end up creating a new string in the cache even if the cache already contains a string having the same content. In short "MyString" == new String("MyString") will always return false.

问题是,如果所有的字符串都缓存在系统中,为什么==返回false,而等于返回true?嗯,这是可能的。如果您创建了一个新的字符串,比如string str = new string(“test”),那么即使缓存已经包含了具有相同内容的字符串,也会在缓存中创建一个新字符串。简言之,“MyString”== new String(“MyString”)将始终返回false。

Java also talks about the function intern() that can be used on a string to make it part of the cache so "MyString" == new String("MyString").intern() will return true.

Java还讨论了可以在字符串中使用的函数intern(),从而使它成为缓存的一部分,因此“MyString”== new string(“MyString”).intern()将返回true。

Note: == operator is much faster than equals just because you are comparing two memory addresses, but you need to be sure that the code isn't creating new String instances in the code. Otherwise you will encounter bugs.

注意:==操作符的速度要快得多,因为您正在比较两个内存地址,但是您需要确保代码不会在代码中创建新的字符串实例。否则就会遇到错误。

#6


124  

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

Make sure you understand why. It's because the == comparison only compares references; the equals() method does a character-by-character comparison of the contents.

一定要弄明白为什么。因为==比较只比较引用;equals()方法对内容进行逐个字符的比较。

When you call new for a and b, each one gets a new reference that points to the "foo" in the string table. The references are different, but the content is the same.

当您调用new for a和b时,每一个都得到一个新的引用,指向字符串表中的“foo”。引用是不同的,但是内容是相同的。

#7


109  

Yea, it's bad...

是的,很糟糕……

== means that your two string references are exactly the same object. You may have heard that this is the case because Java keeps sort of a literal table (which it does), but that is not always the case. Some strings are loaded in different ways, constructed from other strings, etc., so you must never assume that two identical strings are stored in the same location.

==表示您的两个字符串引用是完全相同的对象。您可能听说过这种情况,因为Java保持了一种文字表(确实如此),但情况并非总是如此。有些字符串以不同的方式加载,由其他字符串组成,等等,所以您不能假设两个相同的字符串存储在同一个位置。

Equals does the real comparison for you.

和你真正的比较。

#8


104  

Yes, == is bad for comparing Strings (any objects really, unless you know they're canonical). == just compares object references. .equals() tests for equality. For Strings, often they'll be the same but as you've discovered, that's not guaranteed always.

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

#9


101  

Java have a String pool under which Java manages the memory allocation for the String objects. See String Pools in Java

Java有一个字符串池,其中Java管理字符串对象的内存分配。参见Java中的字符串池。

When you check (compare) two objects using the == operator it compares the address equality into the string-pool. If the two String objects have the same address references then it returns true, otherwise false. But if you want to compare the contents of two String objects then you must override the equals method.

当您使用==操作符检查(比较)两个对象时,它将地址平等与字符串池进行比较。如果两个字符串对象具有相同的地址引用,则返回true,否则为false。但是如果要比较两个字符串对象的内容,那么必须重写equals方法。

equals is actually the method of the Object class, but it is Overridden into the String class and a new definition is given which compares the contents of object.

equals实际上是对象类的方法,但是它被覆盖到String类中,并且给出了一个新的定义,用来比较对象的内容。

Example:
    stringObjectOne.equals(stringObjectTwo);

But mind it respects the case of String. If you want case insensitive compare then you must go for the equalsIgnoreCase method of the String class.

但请注意,它尊重字符串的情况。如果您想要区分大小写,那么您必须使用String类的equalsIgnoreCase方法。

Let's See:

让我们来看看:

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

#10


89  

.equals() compares the data in a class (assuming the function is implemented). == compares pointer locations (location of the object in memory).

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

== returns true if both objects (NOT TALKING ABOUT PRIMITIVES) point to the SAME object instance. .equals() returns true if the two objects contain the same data equals() Versus == in Java

==返回true,如果两个对象(不讨论原语)指向相同的对象实例。. =()返回true,如果两个对象包含相同的数据=()和==在Java中。

That may help you.

这可能会帮助你。

#11


88  

== compares object references in Java, and that is no exception for String objects.

==在Java中比较对象引用,对于字符串对象也不例外。

For comparing the actual contents of objects (including String), one must use the equals method.

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

If a comparison of two String objects using == turns out to be true, that is because the String objects were interned, and the Java Virtual Machine is having multiple references point to the same instance of String. One should not expect that comparing one String object containing the same contents as another String object using == to evaluate as true.

如果使用==的两个字符串对象的比较是正确的,那是因为字符串对象被interned,而Java虚拟机有多个引用指向同一个字符串实例。我们不应该期望将包含相同内容的一个字符串对象与另一个字符串对象进行比较。

#12


85  

== performs a reference equality check, whether the 2 objects (strings in this case) refer to the same object in the memory.

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

The equals() method will check whether the contents or the states of 2 objects are the same.

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

Obviously == is faster, but will (might) give false results in many cases if you just want to tell if 2 Strings hold the same text.

显然==更快,但在很多情况下(可能)会给出错误的结果,如果您只是想判断两个字符串是否具有相同的文本。

Definitely the use of equals() method is recommended.

建议使用equals()方法。

Don't worry about the performance. Some things to encourage using String.equals():

不要担心表演。一些鼓励使用String.equals():

  1. 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!
  2. 执行String.equals()第一次检查引用的相等(使用==),如果两个字符串是相同的,则没有进行进一步的计算!
  3. 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.
  4. 如果两个字符串引用不相同,string .equals()将会检查字符串的长度。这也是一个快速操作,因为String类存储字符串的长度,不需要计算字符或代码点。如果长度不同,则不进行进一步检查,我们知道它们不可能相等。
  5. 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.
  6. 只有当我们得到这两个字符串的内容时,才会比较两个字符串的内容,这将是一个简短的比较:不是所有的字符都将被比较,如果我们发现一个不匹配的字符(在两个字符串中相同的位置),就不会检查更多的字符。

When all is said and done, even if we have guarantee that the strings are interns, using the equals() method is still not that overhead that one might think, definitely the recommended way. If you want efficient reference check, then use enums where it is guaranteed by the language specification and implementation that the same enum value will be the same object (by reference).

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

#13


83  

I agree with the answer from zacherates.

我同意zacherates的回答。

But what you can do is to call intern() on your non-literal strings.

但是你能做的是在你的非文字字符串上调用实习生()。

From zacherates example:

从zacherates例子:

// ... but they are not the same object
new String("test") == "test" ==> false 

If you intern the non-literal String equality is true

如果你实习,非文字的字符串等式是正确的。

new String("test").intern() == "test" ==> true 

#14


75  

If you're like me, when I first started using Java, I wanted to use the "==" operator to test whether two String instances were equal, but for better or worse, that's not the correct way to do it in Java.

如果您像我一样,当我第一次使用Java时,我想使用“==”操作符来测试两个字符串实例是否相等,但是无论好坏,这不是用Java实现的正确方法。

In this tutorial I'll demonstrate several different ways to correctly compare Java strings, starting with the approach I use most of the time. At the end of this Java String comparison tutorial I'll also discuss why the "==" operator doesn't work when comparing Java strings.

在本教程中,我将演示几种不同的方法来正确地比较Java字符串,从我大部分时间使用的方法开始。在这个Java字符串比较教程的最后,我还将讨论为什么“==”操作符在比较Java字符串时不起作用。

Option 1: Java String comparison with the equals method Most of the time (maybe 95% of the time) I compare strings with the equals method of the Java String class, like this:

选项1:Java字符串与equals方法的比较(大约95%的时间),我将字符串与Java String类的equals方法进行比较,如下所示:

if (string1.equals(string2))

This String equals method looks at the two Java strings, and if they contain the exact same string of characters, they are considered equal.

此字符串equals方法查看两个Java字符串,如果它们包含完全相同的字符串,则认为它们是相等的。

Taking a look at a quick String comparison example with the equals method, if the following test were run, the two strings would not be considered equal because the characters are not the exactly the same (the case of the characters is different):

如果使用equals方法查看一个快速的字符串比较示例,如果运行以下测试,那么两个字符串将不会被认为是相等的,因为字符不是完全相同的(字符的情况不同):

String string1 = "foo";
String string2 = "FOO";

if (string1.equals(string2))
{
    // this line will not print because the
    // java string equals method returns false:
    System.out.println("The two strings are the same.")
}

But, when the two strings contain the exact same string of characters, the equals method will return true, as in this example:

但是,当两个字符串包含完全相同的字符串时,equals方法将返回true,就像在这个例子中那样:

String string1 = "foo";
String string2 = "foo";

// test for equality with the java string equals method
if (string1.equals(string2))
{
    // this line WILL print
    System.out.println("The two strings are the same.")
}

Option 2: String comparison with the equalsIgnoreCase method

选项2:与equalsIgnoreCase方法的字符串比较。

In some string comparison tests you'll want to ignore whether the strings are uppercase or lowercase. When you want to test your strings for equality in this case-insensitive manner, use the equalsIgnoreCase method of the String class, like this:

在一些字符串比较测试中,您需要忽略字符串是大写还是小写。当您想以这种不区分大小写的方式测试您的字符串时,请使用String类的equalsIgnoreCase方法,如下所示:

String string1 = "foo";
String string2 = "FOO";

 // java string compare while ignoring case
 if (string1.equalsIgnoreCase(string2))
 {
     // this line WILL print
     System.out.println("Ignoring case, the two strings are the same.")
 }

Option 3: Java String comparison with the compareTo method

选项3:Java字符串与compareTo方法的比较。

There is also a third, less common way to compare Java strings, and that's with the String class compareTo method. If the two strings are exactly the same, the compareTo method will return a value of 0 (zero). Here's a quick example of what this String comparison approach looks like:

还有第三种比较少见的比较Java字符串的方法,这是使用String类compareTo方法。如果这两个字符串完全相同,那么compareTo方法将返回一个0(0)的值。下面是这个字符串比较方法的一个简单示例:

String string1 = "foo bar";
String string2 = "foo bar";

// java string compare example
if (string1.compareTo(string2) == 0)
{
    // this line WILL print
    System.out.println("The two strings are the same.")
}

While I'm writing about this concept of equality in Java, it's important to note that the Java language includes an equals method in the base Java Object class. Whenever you're creating your own objects and you want to provide a means to see if two instances of your object are "equal", you should override (and implement) this equals method in your class (in the same way the Java language provides this equality/comparison behavior in the String equals method).

虽然我在写Java中关于平等的概念,但需要注意的是,Java语言中包含了基本Java对象类中的equals方法。当您创建自己的对象时,您希望提供一种方法来查看您的对象的两个实例是否“相等”,您应该在类中重写(并实现)这个equals方法(就像Java语言在String equals方法中提供这种相等/比较行为一样)。

You may want to have a look at this ==, .equals(), compareTo(), and compare()

您可能需要查看这个==,.equals(), compareTo(),并比较()

#15


71  

Function:

功能:

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

Test:

测试:

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

#16


63  

The == operator check if the two references point to the same object or not. .equals() check for the actual string content (value).

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

Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented, and it checks whether two strings have the same value or not.

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

  • Case 1

    案例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.

    原因:在堆的permgen区域中,在字符串池中存储了没有null的字符串。所以s1和s2指向池中相同的对象。

  • Case 2

    案例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.

    原因:如果您使用new关键字创建一个字符串对象,则在堆上分配一个单独的空间。

#17


47  

== compares the reference value of objects whereas the equals() method present in the java.lang.String class compares the contents of the String object (to another object).

==比较对象的引用值,而在java.lang中显示equals()方法。String类比较字符串对象(指向另一个对象)的内容。

#18


45  

I think that when you define a String you define an object. So you need to use .equals(). When you use primitive data types you use == but with String (and any object) you must use .equals().

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

#19


38  

If the equals() method is present in the java.lang.Object class, and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the == operator is expected to check the actual object instances are same or not.

如果equals()方法存在于java.lang中。对象类,它将检查对象状态的等价性!也就是说,对象的内容。而==操作符将检查实际对象实例是否相同。

Example

例子

Consider two different reference variables, str1 and str2:

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

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

If you use the equals()

如果使用equals()

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

You will get the output as TRUE if you use ==.

如果使用==,则输出为TRUE。

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

Now you will get the FALSE as output, because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() a new object is created every time.

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

#20


36  

Operator == is always meant for object reference comparison, whereas the String class .equals() method is overridden for content comparison:

操作符==总是用于对象引用比较,而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)

#21


32  

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.

在Java中,当“==”操作符用于比较两个对象时,它会检查对象是否在内存中引用相同的位置。换句话说,它检查两个对象名称是否基本引用相同的内存位置。

The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

Java String类实际上覆盖了对象类中的默认equals()实现——它重写了方法,使它只检查字符串的值,而不是检查它们在内存中的位置。这意味着如果您调用equals()方法来比较两个字符串对象,那么只要字符的实际序列是相等的,那么这两个对象都是相等的。

The == operator checks if the two strings are exactly the same object.

操作符检查两个字符串是否完全相同。

The .equals() method check if the two strings have the same value.

方法检查两个字符串是否具有相同的值。

#22


32  

All objects are guaranteed to have a .equals() method since Object contains a method, .equals(), that returns a boolean. It is the subclass' job to override this method if a further defining definition is required. Without it (i.e. using ==) only memory addresses are checked between two objects for equality. String overrides this .equals() method and instead of using the memory address it returns the comparison of strings at the character level for equality.

所有对象都保证有一个.equals()方法,因为对象包含一个方法,.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.

一个关键的说明是字符串存储在一个块池中,因此一旦字符串被创建,它就会永远存储在同一个地址的程序中。字符串不会改变,它们是不可变的。这就是为什么如果您要处理大量的字符串处理,那么使用常规字符串连接是一个坏主意。相反,您将使用提供的StringBuilder类。记住,这个字符串的指针可以改变,如果你有兴趣看看两个指针是否相同==将是一个很好的方法。字符串本身不需要。

#23


32  

You can also use the compareTo() method to compare two Strings. If the compareTo result is 0, then the two strings are equal, otherwise the strings being compared are not equal.

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

The == compares the references and does not compare the actual strings. If you did create every string using new String(somestring).intern() then you can use the == operator to compare two strings, otherwise equals() or compareTo methods can only be used.

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