覆盖 .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));
}
}
第 1 行返回 true,同时将两个字符串与 == operator.I 进行比较,认为 e1 和 e2 的 "Jon" 和 "Smith" 将具有两个不同的引用(内存位置)。
什么概念让 e1 和 e2 的 "Jon" 和 "Smith" 具有相同的引用?(字符串缓存??!还是巧合?)
这是因为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
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,同时将两个字符串与 == operator.I 进行比较,认为 e1 和 e2 的 "Jon" 和 "Smith" 将具有两个不同的引用(内存位置)。
什么概念让 e1 和 e2 的 "Jon" 和 "Smith" 具有相同的引用?(字符串缓存??!还是巧合?)
这是因为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