演示与Java的字符串比较 [英] Demonstrating string comparison with Java
问题描述
我想演示一下几行代码,在Java中,要比较两个字符串( String
),你必须使用 equals ()
而不是运算符 ==
。
I want to demonstrate with a few line of code that in Java, that to compare two strings (String
), you have to use equals()
instead of the operator ==
.
public static void main(String Args[]) {
String s1 = "Hello";
String s2 = "Hello";
if (s1 == s2)
System.out.println("same strings");
else
System.out.println("different strings");
}
我期待这个输出: code>,因为测试
s1 == s2
我实际上是比较两个引用(即地址)而不是对象的内容。
I was expecting this output : different strings
, because with the test s1 == s2
I'm actually comparing two references (i.e. addresses) instead of the objet's content.
但我实际上有这个输出:相同的字符串
!
But I actually got this output : same strings
!
浏览互联网我发现一些Java实现将优化上述代码,使 s1
和 s2
Browsing the internet I found that some Java implementation will optimize the above code so that s1
and s2
will actually reference the same string.
那么,当比较字符串时,如何使用 ==
(or Objects)in Java?
Well, how can I demonstrate the problem using the ==
operator when comparing Strings (or Objects) in Java ?
推荐答案
编译器在你的情况下做一些优化,使 s1
和 s2
都是同一个对象。你可以使用
The compiler does some optimizations in your case so that s1
and s2
are really the same object. You can work around that by using
String s1 = new String( "Hello" );
String s2 = new String( "Hello" );
然后你有两个不同的对象,文本内容相同。
Then you have two distinct objects with the same text content.
这篇关于演示与Java的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!