==到目前为止,我一直在我的程序中使用运算符来比较我的所有字符串.但是,我遇到了一个错误,将其中一个更改为了.equals(),并修复了该错误.
是==坏?什么时候应该不应该使用它?有什么不同?
我有以下代码行来比较String.str1不等于str2,这是可以理解的,因为它比较了对象引用.但那么为什么s1等于s2?
String s1 = "abc";
String s2 = "abc";
String str1 = new String("abc");
String str2 = new String("abc");
if (s1==s2)
System.out.println("s1==s2");
else
System.out.println("s1!=s2");
if (str1==str2)
System.out.println("str1==str2");
else
System.out.println("str1!=str2");
if (s1==str1)
System.out.println("str1==s1");
else
System.out.println("str1!=s1");
Run Code Online (Sandbox Code Playgroud)
输出:
s1==s2
str1!=str2
str1!=s1
Run Code Online (Sandbox Code Playgroud) public static void main(String[] args){
one();
two();
three();
}
public static void one() {
String s1 = "hill5";
String s2 = "hill" + 5;
System.out.println(s1==s2);
}
public static void two() {
String s1 = "hill5";
int i =5;
String s2 = "hill" + i;
System.out.println(s1==s2);
}
public static void three() {
String s1 = "hill5";
String s2 = "hill" + s1.length();
System.out.println(s1==s2);
}
Run Code Online (Sandbox Code Playgroud)
输出是
true
false
false
Run Code Online (Sandbox Code Playgroud)
字符串文字使用实习过程,然后为什么two()而且three()是假的.我可以理解three()但是two()不清楚.但是需要对这两种情况进行适当的解释.
有人可以解释正确的理由吗?