object1.toString() == object2.toString() [重复]

object1.toString() == object2.toString() [duplicate]

提问人:J28 提问时间:11/28/2014 最后编辑:J28 更新时间:11/28/2014 访问量:125

问:

以下是我比较两个对象引用的主要方法。在覆盖了 Car 类中的方法后,我的问题是为什么下面的“if”条件在应该计算为 true 时计算为 false。有人可以解释一下吗?谢谢。toString()

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 == s2c1.toString() == c2.toString()

Java 对象 引用 String Assignment-Operator

评论

0赞 Maroun 11/28/2014
因为使用 .equals
0赞 Michael Lloyd Lee mlk 11/28/2014
这个问题的第二部分是:stackoverflow.com/questions/16729045/......

答:

1赞 TheLostMind 11/28/2014 #1

好吧,因为比较引用和==

  1. 参考 c1 c2 不同
  2. c1.toString().equals(c2.toString())是比较字符串的正确方法。

评论

0赞 J28 11/28/2014
好吧,我知道equals()是正确的比较方法,但是当下面的计算结果为true时,为什么上面不是呢?字符串 s1 = “abc”;字符串 s2=“abc”;s1==s2 - 计算结果为 true
2赞 Fabien Thouraud 11/28/2014
字符串是不可变的对象,任何修改都会创建一个新实例(如您的 toString() 方法)。
2赞 TheLostMind 11/28/2014
@Jsm - 默认情况下,在对象级别 both 和 compare 引用。因此,他们将返回 c1 不是 c2。您必须覆盖并更改其默认 mplementation,然后使用 .对于 Strings,已经实现(overidden),因此,比较 2 个不同字符串实例的内容==equals()falseequals()c1.equals(c2)equals().equals()
1赞 Michael Lloyd Lee mlk 11/28/2014
> 字符串 s1 = “abc”;字符串 s2=“abc”;s1==s2 因为 “” 不创建新字符串,而是使用字符串池。