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”以具有相同的引用?(字符串缓存??!还是只是巧合?)