java - 无法确定唯一的对象集
问题描述
我正在重写 equals 和 hashcode 方法来定义对象的唯一性,但它似乎不起作用。下面是覆盖等于和哈希码的代码,但它不起作用。还有哪些其他方法可以删除重复项?
public class Test {
private static class Model {
private String firstName;
private String lastName;
public Model(final String firstName, final String lastName){
this.firstName = firstName.trim();
this.lastName = lastName.trim();
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("firstName", firstName).add("lastName", lastName).toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Model model = (Model) o;
return firstName.equalsIgnoreCase(model.firstName) &&
lastName.equalsIgnoreCase(model.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
}
public static void main(String[] args){
final List<Model> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add(new Model("a","b"));
listWithDuplicates.add(new Model("A","b"));
listWithDuplicates.add(new Model("a","B "));
listWithDuplicates.add(new Model("A","B"));
System.out.println(new HashSet<Model>(listWithDuplicates));
}
}
预期:[Model{firstName=a, lastName=b} 实际:[Model{firstName=a, lastName=b}, Model{firstName=A, lastName=b}, Model{firstName=a, lastName=B}, Model {名=A,姓=B}]
解决方案
equalsIgnoreCase
您已经测试了与和不与的相等性equals
:
return firstName.equalsIgnoreCase(model.firstName) &&
lastName.equalsIgnoreCase(model.lastName);
考虑到用于表示字符串的确切大小写,而在hashCode
andfirstName
中进行哈希处理。lastName
为了使其不区分大小写,请将您hasdCode
的设置为全部小写或大写:
@Override
public int hashCode() {
firstName = firstName != null ? firstName.toLowerCase() : firstName;
lastName = lastName != null ? lastName.toLowerCase() : lastName;
return Objects.hash(firstName, lastName);
}
推荐阅读
- jodit - 如何在 Jodit 中创建自定义按钮以将文本包装在代码标签中?
- python - ffmpeg-python 错误,无法加载 mp4 编码器
- java - 如何搜索 RealmObj 的 RealmList 字段
- javascript - 转换旧的 javascript 包以导出 typescript 模块
- python - numpy.ndarray' 对象没有属性 'append
- django - 我可以获取在 django 中更新记录的管理员的姓名吗?
- flutter - 如何在我的谷歌地图上开始绘图?
- python - selenium 使用元素的子元素抓取数据
- html - HTML页面将带有POST的表单传递到没有HTTP服务器的下一页
- python - NameError 与第一个 python 脚本