能否提供10个实际的例子,展示如何重写HashMap中hashCode和equals方法以保证其正确性?
时间: 2024-11-04 16:14:16 浏览: 23
重写`HashMap`的`hashCode()`和`equals()`方法是为了确保当自定义类作为键被存储到`HashMap`中时,键的唯一性和哈希值计算的一致性。以下是一些实际例子:
1. **实例一**:
```java
public class CustomKey {
private String name;
public CustomKey(String name) {
this.name = name;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
CustomKey other = (CustomKey) obj;
return Objects.equals(name, other.name);
}
}
```
在这个例子中,我们基于`name`字段生成`hashCode`并检查两个`CustomKey`是否相等。
2. **实例二**:
```java
public class User {
private String username;
private String email;
// ...
@Override
public int hashCode() {
int result = 17;
result = 31 * result + username.hashCode();
result = 31 * result + email.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
User other = (User) obj;
return username.equals(other.username) && email.equals(other.email);
}
}
```
这里将用户名和邮箱都考虑在内,确保两个用户对象的完全匹配。
3. **实例三**:
```java
public class Address {
private String street;
private String city;
// ...
@Override
public int hashCode() {
int result = 17;
result = 31 * result + street.hashCode();
result = 31 * result + city.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
Address other = (Address) obj;
return street.equals(other.street) && city.equals(other.city);
}
}
```
地址类同样根据街道名和城市名确定哈希码和比较规则。
阅读全文