Java String.equals 与 ==
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/767372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String.equals versus ==
提问by franvergara66
This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working?
这段代码将一个字符串分成标记并将它们存储在一个字符串数组中,然后将一个变量与第一个家进行比较......为什么它不起作用?
public static void main(String...aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos = "Jorman 14988611";
StringTokenizer tokens = new StringTokenizer(strDatos, " ");
int nDatos = tokens.countTokens();
String[] datos = new String[nDatos];
int i = 0;
while (tokens.hasMoreTokens()) {
String str = tokens.nextToken();
datos[i] = str;
i++;
}
//System.out.println (usuario);
if ((datos[0] == usuario)) {
System.out.println("WORKING");
}
}
采纳答案by Alnitak
Use the string.equals(Object other)
function to compare strings, not the ==
operator.
使用string.equals(Object other)
函数来比较字符串,而不是==
运算符。
The function checks the actual contents of the string, the ==
operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==
, but it's better not to rely on that.
该函数检查字符串的实际内容,==
运算符检查对对象的引用是否相等。请注意,字符串常量通常是“内嵌的”,因此实际上可以将具有相同值的两个常量与 进行比较==
,但最好不要依赖它。
if (usuario.equals(datos[0])) {
...
}
NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos
array otherwise you'll get an array-out-of-bounds exception.
注意:比较是在 'usuario' 上完成的,因为这保证在您的代码中非空,尽管您仍然应该检查datos
数组中是否确实有一些标记,否则您将收到数组越界异常.
回答by Bhushan Bhangale
Instead of
代替
datos[0] == usuario
use
用
datos[0].equals(usuario)
==
compares the reference of the variable where .equals()
compares the values which is what you want.
==
比较变量的引用,其中.equals()
比较您想要的值。
回答by Michael Klement
You should use string equalsto compare two strings for equality, not operator == which just compares the references.
您应该使用字符串等于来比较两个字符串的相等性,而不是运算符 == 只是比较引用。
回答by Michal Bernhard
It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings- string literals are interned (see String.intern()
) during compilation - so when you write for example "hello world"
in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal"
) and second is constructed during runtime ie. with "new" keyword like new String("i am string literal")
, the ==
(equality) operator returns false, because both of them are different instances of the String
class.
值得注意的是,在某些情况下,使用“==”运算符可能会导致预期的结果,因为 java 处理字符串的方式- 字符串文字String.intern()
在编译期间被插入(请参阅) - 所以当你"hello world"
在两个类中编写例如将这些字符串与“==”进行比较,您可以得到结果:true,这是根据规范预期的;当您比较相同的字符串(如果它们具有相同的值)时,第一个是字符串文字(即通过 定义"i am string literal"
),第二个是在运行时构造的,即。使用“new”关键字 like new String("i am string literal")
,==
(相等)运算符返回 false,因为它们都是String
该类的不同实例。
Only right way is using .equals()
-> datos[0].equals(usuario)
.==
says only if two objects are the same instance of object (ie. have same memory address)
唯一正确的方法是使用.equals()
-> datos[0].equals(usuario)
。==
仅当两个对象是对象的同一实例(即具有相同的内存地址)时才说
Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language
更新: 01.04.2013 我更新了这篇文章,因为下面的评论在某种程度上是正确的。最初我声明实习 (String.intern) 是 JVM 优化的副作用。虽然它确实节省了内存资源(这就是我所说的“优化”),但它主要是语言的特性
回答by finnw
It will also work if you call intern()
on the string before inserting it into the array.
Interned strings are reference-equal (==
) if and only if they are value-equal (equals()
.)
如果您intern()
在将字符串插入数组之前调用它,它也将起作用。实习字符串是引用相等 ( ==
) 当且仅当它们是值相等 ( equals()
.)
public static void main (String... aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos="Jorman 14988611";
StringTokenizer tokens=new StringTokenizer(strDatos, " ");
int nDatos=tokens.countTokens();
String[] datos=new String[nDatos];
int i=0;
while(tokens.hasMoreTokens()) {
String str=tokens.nextToken();
datos[i]= str.intern();
i++;
}
//System.out.println (usuario);
if(datos[0]==usuario) {
System.out.println ("WORKING");
}
回答by HariShankar
equals()
function is a method of Object
class which should be overridden by programmer. String
class overrides it to check if two strings are equal i.e. in content and not reference.
equals()
function 是一个Object
类的方法,应该被程序员覆盖。String
类覆盖它以检查两个字符串是否相等,即内容而不是引用。
==
operator checks if the references of both the objects are the same.
==
运算符检查两个对象的引用是否相同。
Consider the programs
考虑程序
String abc = "Awesome" ;
String xyz = abc;
if(abc == xyz)
System.out.println("Refers to same string");
Here the abc
and xyz
, both refer to same String
"Awesome"
. Hence the expression (abc == xyz)
is true
.
这里的abc
和xyz
,都指同一个String
"Awesome"
。因此表达式(abc == xyz)
为true
。
String abc = "Hello World";
String xyz = "Hello World";
if(abc == xyz)
System.out.println("Refers to same string");
else
System.out.println("Refers to different strings");
if(abc.equals(xyz))
System.out.prinln("Contents of both strings are same");
else
System.out.prinln("Contents of strings are different");
Here abc
and xyz
are two different strings with the same content "Hello World"
. Hence here the expression (abc == xyz)
is false
where as (abc.equals(xyz))
is true
.
这里abc
和xyz
是具有相同内容的两个不同字符串"Hello World"
。因此这里的表达式(abc == xyz)
是false
where as (abc.equals(xyz))
is true
。
Hope you understood the difference between ==
and <Object>.equals()
希望你明白之间的差别==
,并<Object>.equals()
Thanks.
谢谢。
回答by Harry He
Let's analyze the following Java, to understand the identity and equality of Strings:
下面我们来分析一下Java,了解Strings的恒等性:
public static void testEquality(){
String str1 = "Hello world.";
String str2 = "Hello world.";
if (str1 == str2)
System.out.print("str1 == str2\n");
else
System.out.print("str1 != str2\n");
if(str1.equals(str2))
System.out.print("str1 equals to str2\n");
else
System.out.print("str1 doesn't equal to str2\n");
String str3 = new String("Hello world.");
String str4 = new String("Hello world.");
if (str3 == str4)
System.out.print("str3 == str4\n");
else
System.out.print("str3 != str4\n");
if(str3.equals(str4))
System.out.print("str3 equals to str4\n");
else
System.out.print("str3 doesn't equal to str4\n");
}
When the first line of code String str1 = "Hello world."
executes, a string \Hello world."
is created, and the variable str1
refers to it. Another string "Hello world."
will not be created again when the next line of code executes because of optimization. The variable str2
also refers to the existing ""Hello world."
.
当第一行代码String str1 = "Hello world."
执行时,\Hello world."
会创建一个字符串,变量str1
引用它。"Hello world."
由于优化,在下一行代码执行时不会再次创建另一个字符串。该变量str2
也指现有的""Hello world."
.
The operator ==
checks identity of two objects (whether two variables refer to same object). Since str1
and str2
refer to same string in memory, they are identical to each other. The method equals
checks equality of two objects (whether two objects have same content). Of course, the content of str1
and str2
are same.
运算符==
检查两个对象的身份(两个变量是否引用同一个对象)。由于str1
和str2
引用内存中的相同字符串,因此它们彼此相同。该方法equals
检查两个对象的相等性(两个对象是否具有相同的内容)。当然,内容str1
和str2
相同。
When code String str3 = new String("Hello world.")
executes, a new instance of string with content "Hello world."
is created, and it is referred to by the variable str3
. And then another instance of string with content "Hello world."
is created again, and referred to by
str4
. Since str3
and str4
refer to two different instances, they are not identical, but their
content are same.
代码String str3 = new String("Hello world.")
执行时,"Hello world."
会创建一个包含内容的新字符串实例,并由变量 引用str3
。然后"Hello world."
再次创建另一个包含内容的字符串实例,并由
str4
. 由于str3
和str4
指的是两个不同的实例,因此它们并不相同,但它们的内容相同。
Therefore, the output contains four lines:
因此,输出包含四行:
Str1 == str2
Str1 equals str2
Str3! = str4
Str3 equals str4
回答by Himanshu Mohta
==
operator compares the reference of an object in Java. You can use string's equals
method .
==
运算符比较 Java 中对象的引用。您可以使用字符串的equals
方法。
String s = "Test";
if(s.equals("Test"))
{
System.out.println("Equal");
}
回答by mreaevnia
If you are going to compare any assigned value of the string i.e. primitive string, both "==" and .equals will work, but for the new string object you should use only .equals, and here "==" will not work.
如果您要比较字符串的任何指定值,即原始字符串,“==”和 .equals 都可以使用,但是对于新的字符串对象,您应该只使用 .equals,而这里的“==”将不起作用。
Example:
例子:
String a = "name";
String b = "name";
if(a == b)
and (a.equals(b))
will return true.
if(a == b)
并且(a.equals(b))
将返回true。
But
但
String a = new String("a");
In this case if(a == b)
will return false
在这种情况下if(a == b)
会返回false
So it's better to use the .equals
operator...
所以最好使用.equals
运算符...
回答by Harrydev
Use Split rather than tokenizer,it will surely provide u exact output for E.g:
使用 Split 而不是分词器,它肯定会为您提供准确的输出,例如:
string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}
After this I am sure you will get better results.....
在此之后,我相信你会得到更好的结果......