【发布时间】:2015-01-26 23:05:03
【问题描述】:
以下是我比较两个对象引用的主要方法。重写了 Car 类中的 toString() 方法后,我的问题是为什么下面的“if”条件在它们应该评估为 true 时评估为 false。有人可以解释一下吗?谢谢。
public static void main(String[] args){
Car c1 = new Car(2829,"white");
Car c2 = new Car(2829,"white");
if(c1 == c2)
System.out.println(true);
else
System.out.println(false);
String sc1 = c1.toString();
String sc2 = c2.toString();
if(sc1 == sc2)
System.out.println("it's equal");
else
System.out.println("it's not!");
}
public class Car {
private int regNo;
private String color;
protected void start(){
System.out.println("Car Started!");
}
public Car(int regNo, String color){
this.regNo = regNo;
this.color = color;
}
@Override
public String toString() {
return "Car-"+regNo;
}
}
说,我有两个字符串s1="abc" and s2 = "abc"。现在,s1 == s2 评估为 true 那么为什么在上面的代码中 c1.toString() == c2.toString() 评估为 false 是我的问题?
【问题讨论】:
-
因为使用
equals。 -
这个问题的第二部分是重复的:stackoverflow.com/questions/16729045/…
标签: java object reference tostring assignment-operator