如何比较爪哇的字符串?

发布于 2025-01-19 17:54:31 字数 162 浏览 0 评论 0 原文

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

== 不好吗?什么时候应该使用它,什么时候不应该使用它?有什么区别?

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

一场春暖 2025-01-26 17:54:31

== 测试参考平等(它们是否是同一对象)。

.equals()测试值平等(它们是否包含相同的数据)。

objects.equals()在调用 null 之前检查 .equals(),因此您不必(如JDK7,也可用,也可用在 guava )。

因此,如果要测试两个字符串是否具有相同的值,则可能要使用 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
Objects.equals(null, null) // --> true

来自Java语言规范 == 和!=

== 可以使用类型字符串的参考文献,这样的平等测试确定两个操作数是否指的是相同的 string string < /代码>对象。结果是 false ,如果操作数是不同的字符串对象,即使它们包含相同的字符序列(§3.10.5 s t 可以通过方法调用 s.equal(t)

您几乎总是想要使用 objects.equals()。在稀有的情况下,您知道您正在处理实习字符串,您 can 使用 ==

来自 jls 3.10.5。 字符串文字

此外,字符串文字始终涉及类相同的实例 string 。这是因为字符串文字 - 或更一般而言,是恒定表达式值的字符串(§15.28) - 是“实习”,以共享唯一实例,使用方法 string.intern.intern

也可以在

考虑

忽略案例的价值平等。但是,请注意,此方法在各种与区域相关的情况下可能会产生意外结果,请参见

String 的内容与任何 charsequence 的内容进行比较(自Java 1.5以来可用)。在进行平等比较之前,请您不得不将StringBuffer等变成字符串,但请将NULL检查给您。

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

.equals() tests for value equality (whether they contain the same data).

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

Consequently, if you want to test whether two strings have the same value you will probably want to use 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
Objects.equals(null, null) // --> true

From the Java Language Specification JLS 15.21.3. Reference Equality Operators == and !=:

While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters (§3.10.5, §3.10.6). The contents of two strings s and t can be tested for equality by the method invocation s.equals(t).

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

From JLS 3.10.5. String Literals:

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.

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

Other Methods To Consider

String.equalsIgnoreCase() value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see this question.

String.contentEquals() compares the content of the String with the content of any CharSequence (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.

盛装女皇 2025-01-26 17:54:31

== 测试对象引用, .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";

,但要注意nulls!

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

因此,如果您知道 foostring1 可能为null,请告诉读者,通过编写

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

以下内容较短,但是不太明显,它检查了null:null:

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

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

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.

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:

String nullString1 = null;
String nullString2 = null;

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

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

So if you know that fooString1 may be null, tell the reader that by writing

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

The following are shorter, but it’s less obvious that it checks for null:

System.out.print("bar".equals(fooString1));  // "bar" is never null
System.out.print(Objects.equals(fooString1, "bar"));  // Java 7 required
套路撩心 2025-01-26 17:54:31

== 比较对象引用。

.equals() 比较字符串值。

有时 == 会产生比较 String 值的错觉,如下例所示:

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

这是因为当您创建任何 String 文字时,JVM 首先在 String 池中搜索该文字,如果找到匹配项,同样的引用将被赋予新的字符串。因此,我们得到:

(a==b) ===> true

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

但是,== 在以下情况下会失败:

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

在这种情况下,对于 new String("test") 语句 new String 将在堆上创建,并且该引用将被赋予 b,因此 b 将在堆上获得引用,而不是在字符串池中。

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

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

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

== compares Object references.

.equals() compares String values.

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:

(a==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.

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:

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

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

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

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

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.

醉生梦死 2025-01-26 17:54:31

== 操作员检查两个字符串是否完全是同一对象。

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

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.

无边思念无边月 2025-01-26 17:54:31

Java中的字符串是不变的。这意味着,每当您尝试更改/修改字符串时,您就会获得新实例。您无法更改原始字符串。这样做是为了使这些字符串实例可以缓存。典型的程序包含大量字符串参考,缓存这些实例可以降低内存足迹并提高程序的性能。

当使用==操作员进行字符串比较时,您没有比较字符串的内容,而是在比较内存地址。如果他们俩都相等,则否则将返回真和错误。而在字符串中等于字符串内容。

因此,问题是,如果所有字符串都在系统中缓存,那么 == 如何返回false而等于返回true?好吧,这是可能的。如果您制作一个新的字符串,例如 String str = new String(“ Testing”),即使缓存已经包含具有相同内容的字符串,您最终会在缓存中创建一个新字符串。简而言之,“ mystring” ==新字符串(“ mystring”)将始终返回false。

Java还讨论了可以在字符串上使用的函数Interal(),以使其成为缓存的一部分,因此“ myString” ==新字符串(“ mystring”)。intern()将返回true true true 。

注意:==操作员仅仅是因为您要比较两个内存地址,但是您需要确保代码没有在代码中创建新的字符串实例。否则,您将遇到错误。

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.

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.

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.

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.

萌辣 2025-01-26 17:54:31
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 的新名称时,每个参考都会在字符串表中指向“ foo” 的新参考。参考是不同的,但内容是相同的。

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.

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.

终止放荡 2025-01-26 17:54:31

是的,这很糟糕...

== 意味着您的两个字符串引用完全相同的对象。您可能听说过这种情况,因为 Java 保留了某种文字表(确实如此),但情况并非总是如此。某些字符串以不同的方式加载,从其他字符串构造等,因此您绝不能假设两个相同的字符串存储在同一位置。

Equals 为您进行真正的比较。

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.

Equals does the real comparison for you.

东走西顾 2025-01-26 17:54:31

是的, == 对比较字符串不利(除非您知道它们是规范的)。 == 只需比较对象引用。 .equals()测试平等。对于字符串而言,通常它们会相同,但是正如您发现的那样,这并不能始终保证。

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.

墨离汐 2025-01-26 17:54:31

Java有一个字符串池,Java管理字符串对象的内存分配。 java 字符串池

请参阅 比较)两个对象使用 == 运算符将地址相等性比较到字符串池中。如果两个字符串对象具有相同的地址引用,则它返回 true ,否则 false 。但是,如果要比较两个字符串对象的内容,则必须覆盖 equals 方法。

等于实际上是对象类的方法,但是它被覆盖到字符串类中,并给出了一个新的定义,以比较对象的内容。

Example:
    stringObjectOne.equals(stringObjectTwo);

但是请注意,它尊重字符串的情况。如果您想要案例不敏感的比较,则必须选择字符串类的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

Java have a String pool under which Java manages the memory allocation for the String objects. See String Pools in 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.

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.

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.

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
梦魇绽荼蘼 2025-01-26 17:54:31

我同意Zacherates的答案。

但是,您可以做的是在非文字字符串上调用 intern()

从zacherates示例中:

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

如果您实习,则非字符串平等为 true

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

I agree with the answer from zacherates.

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

From zacherates example:

// ... 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 
十秒萌定你 2025-01-26 17:54:31

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

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

如果使用 == 对两个 String 对象进行比较,则是 true ,那是因为 String 对象被实施,Java虚拟机的多个引用指向 String 的同一实例。不应该期望使用 == 将一个字符串字符串对象进行比较对象,以评估为 true 代码>。

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

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

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.

一曲爱恨情仇 2025-01-26 17:54:31

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

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

这可能会对您有所帮助。

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

== 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

That may help you.

过气美图社 2025-01-26 17:54:31

== 执行A 参考等效检查,是否是2个对象(在这种情况下)请参阅内存中的相同对象。

equals()方法将检查2个对象的目录还是状态是相同的。

显然, == 更快,但是如果您只想告诉2 String s持有相同的文本,则在许多情况下(可能)给出错误的结果。

绝对建议使用 equals()方法。

不必担心表演。鼓励使用 string.equals()的某些事情:

  1. string.equals()的实现首先检查参考等值(使用 == ),如果通过参考将两个字符串相同,则不会进行进一步的计算!
  2. 如果2个字符串引用不相同,则接下来将检查字符串的长度。这也是一个快速操作,因为 String 类存储字符串的长度,无需计算字符或代码点。如果长度有所不同,则没有进一步检查,我们知道它们不能相等。
  3. 只有我们得到这两个字符串的内容才能实际比较,这将是一个简短的比较:如果我们找到一个不匹配的字符(在两个字符串中的位置相同的位置,都会比较所有字符),不会检查其他字符。

当一切都说完之后,即使我们保证字符串是实习生,使用 equals()方法仍然不是人们可能会想到的开销,绝对是推荐的方式。如果您需要有效的参考检查,请使用语言规范和实现来保证的枚举,即相同的枚举值将是同一对象(通过参考)。

== 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.

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 the equals() method is recommended.

Don't worry about the performance. Some things to encourage using 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. 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.
  3. 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.

When all is said and done, even if we have a 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 an 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).

真心难拥有 2025-01-26 17:54:31

如果您像我一样,当我第一次开始使用 Java 时,我想使用“==”运算符来测试两个 String 实例是否相等,但无论好坏,这都不是 Java 中的正确方法。

在本教程中,我将演示几种正确比较 Java 字符串的不同方法,从我最常使用的方法开始。在本 Java 字符串比较教程的最后,我还将讨论为什么“==”运算符在比较 Java 字符串时不起作用。

选项1:使用equals方法比较Java字符串
大多数时候(也许是 95% 的时间)我用 Java String 类的 equals 方法比较字符串,如下所示:

if (string1.equals(string2))

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

看一下使用 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.")
}

但是,当两个字符串包含完全相同的字符串时,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.")
}

选项 2:使用 equalsIgnoreCase 方法进行字符串比较

在某些字符串比较测试中,您需要忽略字符串是否为大写或小写。当您想以这种不区分大小写的方式测试字符串是否相等时,请使用 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.")
 }

选项 3:使用compareTo 方法进行 Java String 比较

还有第三种方法比较 Java 字符串的不太常见的方法,那就是使用 String 类的compareTo 方法。如果两个字符串完全相同,compareTo 方法将返回值 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.")
}

当我在 Java 中撰写有关相等概念的文章时,请务必注意 Java 语言在基本 Java Object 类中包含 equals 方法。每当您创建自己的对象并且想要提供一种方法来查看对象的两个实例是否“相等”时,您应该在类中重写(并实现)此 equals 方法(与 Java 语言提供的方式相同) String equals 方法中的这种相等/比较行为)。

您可能想看看这个==,。 equals()、compareTo() 和compare()

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.

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.

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:

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.

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

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:

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

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

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:

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

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

肥爪爪 2025-01-26 17:54:31

功能:

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

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);
坦然微笑 2025-01-26 17:54:31

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

请注意, .equals()方法属于类对象(所有类的超级类)。您需要按照类要求覆盖它,但是对于字符串,它已经实现,并且检查两个字符串是否具有相同的值。

  • 案例1

     字符串s1 =“ stack Overflow”;
    字符串S2 =“堆栈溢出”;
    S1 == S2; //真的
    S1.Equals(S2); //真的
     

    原因:创建的无零的字符串文字存储在Heap的Permgen区域的字符串池中。因此,s1和s2都指向池中的同一对象。

  • 案例2

     字符串s1 = new String(“ stack Overflow”);
    字符串S2 =新字符串(“堆栈溢出”);
    S1 == S2; //错误的
    S1.Equals(S2); //真的
     

    :如果您使用 new 关键字创建一个字符串对象。

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

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.

  • 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.

小梨窩很甜 2025-01-26 17:54:31

== 比较对象的参考值,而 equals()方法中存在 java.lang.string 类中的方法比较<代码>字符串对象(到另一个对象)。

== 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).

别想她 2025-01-26 17:54:31

我认为当你定义一个String时你就定义了一个对象。所以你需要使用.equals()。当您使用原始数据类型时,您可以使用==,但对于String(以及任何对象),您必须使用.equals()

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().

沫离伤花 2025-01-26 17:54:31

如果 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()每次都会创建一个新对象。

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.

Example

Consider two different reference variables, str1 and str2:

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

If you use the equals()

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

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

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.

爱本泡沫多脆弱 2025-01-26 17:54:31

运算符 == 始终用于对象引用比较,而 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)

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

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)
扎心 2025-01-26 17:54:31

所有对象都可以保证具有 .equals()方法,因为对象包含 .equals(),返回布尔值。如果需要进一步的定义定义,则覆盖此方法是子类的工作。没有它(即使用 == ),仅在两个对象之间检查内存地址以保持平等。字符串覆盖此 .equals()方法,而不是使用内存地址,而是返回字符级别的字符串比较以获得平等。

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

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.

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.

半葬歌 2025-01-26 17:54:31

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

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

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.

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.

九八野马 2025-01-26 17:54:31

在Java中,当使用 == 运算符比较2个对象时,它检查对象是否涉及内存中的同一位置。换句话说,它检查了两个对象名称是否基本上是引用了同一内存位置。

Java 字符串类实际覆盖默认 equals() object 类中实现 - 它覆盖了该方法,以便仅检查值字符串,而不是记忆中的位置。
这意味着,如果您调用 equals()进行比较2 字符串对象的方法,那么只要字符的实际顺序相等,两个对象都被认为是相等的。

== 操作员检查两个字符串是否完全是同一对象。

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

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.

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.

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文