Wiki Markup |
---|
Objects that serve as keys in ordered sets and maps should be immutable. When some fields must be mutable, ensure that the {{equals()}}, {{hashCode()}} and {{compareTo()}} methods must consider only immutable state whilewhen comparing objects. Violations of this rule can produce inconsistent orderings in collections. The documentation of {{java.util.Interface Set<E>}} and {{java.util.Interface Map<K,V>}} warn against this \[[API 2006|AA. Bibliography#API 06]\]: |
...
This noncompliant code example defines a mutable class Employee
that consists of the fields name
and salary
, whose values can be changed using the respective setters. The equals()
method is overridden to provide a comparison facility by employee name.
Code Block |
---|
|
// Mutable class Employee
class Employee {
private String name;
private double salary;
Employee(String empName, double empSalary) {
this.name = empName;
this.salary = empSalary;
}
public void setEmployeeName(String empName) {
this.name = empName;
}
// ... including a hashCode implementation
@Override public boolean equals(Object o) {
if (!(o instanceof Employee)) {
return false;
}
Employee emp = (Employee)o;
return emp.name.equals(name);
}
}
// Client code
Map<Employee, Calendar> map = new ConcurrentHashMap<Employee, Calendar>();
// ...
|
...
Code Block |
---|
|
// Mutable class Employee
class Employee {
private String name;
private double salary;
private final long employeeID; // Unique for each Employee
Employee(String name, double salary, long empID) {
this.name = name;
this.salary = salary;
this.employeeID = empID;
}
// ... including a hashCode implementation
@Override public boolean equals(Object o) {
if (!(o instanceof Employee)) {
return false;
}
Employee emp = (Employee)o;
return emp.employeeID == employeeID;
}
}
// Client code remains same
Map<Employee, Calendar> map = new ConcurrentHashMap<Employee, Calendar>();
// ...
|
...