【问题标题】:object1.toString() == object2.toString() [duplicate]object1.toString() == object2.toString() [重复]
【发布时间】: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 是我的问题?

【问题讨论】:

标签: java object reference tostring assignment-operator


【解决方案1】:

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

  1. 引用 c1 与 不一样 c2
  2. c1.toString().equals(c2.toString()) 是比较字符串的正确方法。

【讨论】:

  • 好吧,我知道 equals() 是比较的正确方法,但是当下面的评估为真时,为什么上面的不是?字符串 s1 = "abc";字符串 s2="abc"; s1==s2 - 计算结果为真
  • 字符串是不可变的对象,任何修改都会创建一个新实例(如您的 toString() 方法)。
  • @Jsm - 默认情况下,在 object 级别,==equals() 比较引用。所以,他们会返回false c1 is not c2。您必须覆盖 equals(),然后更改其默认 实现,然后使用c1.equals(c2)。对于字符串,equals() 已经实现(覆盖),因此,.equals() 比较 contents 的 2 个 不同 字符串实例。
  • > 字符串 s1 = "abc";字符串 s2="abc"; s1==s2 因为 "" 不创建新字符串,而是使用字符串池化。
猜你喜欢
  • 1970-01-01
  • 2014-11-13
  • 2013-10-14
  • 1970-01-01
  • 2018-01-06
  • 2012-05-22
  • 1970-01-01
  • 2018-01-21
  • 2013-11-13
相关资源
最近更新 更多