简体   繁体   English

覆盖.equals()方法(比较字符串时==返回true)!

[英]Overriding .equals() method (== returned true while comparing Strings)!

public class Employee {

private String firstName;
private String lastName;
private int age;

public Employee(String firstName, String lastName, int age) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}

public boolean equals(Employee s) {
    if (this.firstName==s.firstName  && this.lastName == s.lastName) { //Line 1
        return true;
    }
    return false;
}

public static void main(String agrs[]) {

    Employee e1 = new Employee("Jon", "Smith", 30);
    Employee e2 = new Employee("Jon", "Smith", 35);

    System.out.println(e1.equals(e2));
}

}

Line 1 returned true while comparing two Strings with == operator.I thought "Jon" and "Smith" of e1 and e2 will be having two different references(memory location). 第1行在将两个String与==运算符进行比较时返回true。我认为e1和e2的“ Jon”和“ Smith”将具有两个不同的引用(内存位置)。

What concept is taking care of "Jon" and "Smith" of e1 and e2 to have same references?(String caching??! or Is it just coincidental?) 什么概念正在照顾e1和e2的“ Jon”和“ Smith”以具有相同的引用?(字符串缓存?!还是只是巧合?)

This is because of string interning . 这是因为字符串实习 The string literals "Jon" and "Smith" are compiled into the same string and saved in the string constant pool by the compiler. 字符串文字“ Jon”和“ Smith”被编译为相同的字符串,并由编译器保存在字符串常量池中。 Hence in this case, both constructors would reference the same instance. 因此,在这种情况下,两个构造函数都将引用相同的实例。

You can see the difference using the below: 您可以使用以下内容查看差异:

Employee e1 = new Employee("Jon", "Smith", 30);
Employee e2 = new Employee("Jon", "Smith", 35);
Employee e3 = new Employee(new String("Jon"), new String("Smith"), 35);

System.out.println(e1.equals(e2));  // true
System.out.println(e1.equals(e3));  // false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM