==到目前为止,我一直在我的程序中使用运算符来比较我的所有字符串.但是,我遇到了一个错误,将其中一个更改为了.equals(),并修复了该错误.
是==坏?什么时候应该不应该使用它?有什么不同?
我今天换了讲师,他说我用了一个奇怪的代码.(他说最好使用.equals,当我问为什么时,他回答"因为它是!")
所以这是一个例子:
if (o1.equals(o2))
{
System.out.println("Both integer objects are the same");
}
Run Code Online (Sandbox Code Playgroud)
而不是我习惯的:
if (o1 == o2)
{
System.out.println("Both integer objects are the same");
}
Run Code Online (Sandbox Code Playgroud)
这两者之间有什么区别.为什么他的方式(使用.equals)更好?
通过快速搜索找到了这个,但我无法理解这个答案:
我正面临着这条线的问题(下面评论):
System.out.println("Using == ::"+s3==s4)
Run Code Online (Sandbox Code Playgroud)
哪个输出false.
但是,System.out.println(s3==s4)产出true.
现在,我无法理解为什么我得到这个结果:
public class string {
public static void main(String[] args){
String s3="Shantanu";
String s4=s3;
String s1=new String("java");
String s2=new String("javaDeveloper");
System.out.println("Using Equals Method::"+s1.equals(s2));
System.out.println("Using Equals Method::"+s3.equals(s4));
System.out.println("Using == ::"+s3==s4);//Problem is here in this line
System.out.println(s1+"Directly printing the s2 value which is autocasted from superclass to string subclass ");
System.out.println("Directly printing the s1 value which is autocasted from superclass to string subclass "+s2);
System.out.println(s3);
}
}
Run Code Online (Sandbox Code Playgroud)
Output-Using Equals Method::false …