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

时间:2015-01-18 14:20:34

标签: java caching equals referenceequals

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));
}

}

第1行在将两个字符串与==运算符进行比较时返回true。我认为e1和e2的“Jon”和“Smith”将具有两个不同的引用(内存位置)。

什么概念照顾e1和e2的“Jon”和“Smith”有相同的引用?(字符串缓存??!还是巧合?)

1 个答案:

答案 0 :(得分:1)

这是因为string interning。字符串文字“Jon”和“Smith”被编译成相同的字符串,并由编译器保存在字符串常量池中。因此,在这种情况下,两个构造函数都将引用相同的实例。

您可以使用以下内容查看差异:

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