gpt4 book ai didi

java - 从哈希集中删除重复项的逻辑

转载 作者:行者123 更新时间:2023-11-29 04:35:32 24 4
gpt4 key购买 nike

这是场景。仅当 3 个字段中的 2 个值相同时,我才想避免重复。 ID 会有所不同,但如果名称和地址都相同,则应避免这种情况。

我尝试了以下代码,其中添加了一些名称、ID 和地址

HashSet<Employee> mySet = new HashSet<Employee>();
mySet.add(new Employee (1,"a","xxx"));
mySet.add(new Employee(2,"a", "yyy"));

for(Employee emp : mySet) {
System.out.println(emp.getId() + " " + emp.getName()+" "+emp.getAddress());
}

我有一个 Employee 类,其中包含我选择的 setter 和 getter 以及构造函数。

如果要重复名称和地址(两者),我想避免打印。

1个xxx
2 一个 xxx应避免上述情况

你能帮我逻辑吗?

最佳答案

在您的Employee 类中,根据您的规则实现equals()hashCode():

class Employee {
private int id;
private String name;
private String address;

public Employee(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(name, employee.name) &&
Objects.equals(address, employee.address);
}

@Override
public int hashCode() {
return Objects.hash(name, address);
}
}

关于java - 从哈希集中删除重复项的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41759072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com