Compare two objects with .equals() and == operator

前端 未结 15 1608
礼貌的吻别
礼貌的吻别 2020-11-22 01:13

I constructed a class with one String field. Then I created two objects and I have to compare them using == operator and .equals() too

15条回答
  •  暖寄归人
    2020-11-22 01:32

    If you dont need to customize the default toString() function, another way is to override toString() method, which returns all attributes to be compared. then compare toString() output of two objects. I generated toString() method using IntelliJ IDEA IDE, which includes class name in the string.

    public class Greeting {
    private String greeting;
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        return this.toString().equals(obj.toString());
    }
    
    @Override
    public String toString() {
        return "Greeting{" +
                "greeting='" + greeting + '\'' +
                '}';
    }
    }
    

提交回复
热议问题