gpt4 book ai didi

java - 如何将具有唯一字段的对象添加到 Set

转载 作者:行者123 更新时间:2023-11-29 08:43:35 25 4
gpt4 key购买 nike

如何用唯一字段填充对象集合?

例如,我有一个类 Person,它有一个名为 name 的唯一字段,因此如果我添加到 Set 一个具有重复名称的对象,则不应添加它。

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
Set<Person> objList = new HashSet<Person>();
objList.add(new Person("John", "New York", "Accountant"));
objList.add(new Person("Bill", "London", "Manager"));
objList.add(new Person("John", "New York", "Driver"));// this object should not be added

for(Person o : objList){
System.out.println(o.name);//here should printed only John and Bill
}
}
}

class Person {
String name;//must be unique
String city;
String position;

public Person(String c_name, String c_city, String c_position){
this.name = c_name;
this.city = c_city;
this.position = c_position;
}
}

最佳答案

换句话说,你的意思是这个人的名字定义了它的身份。您可以通过覆盖 equals(Object)hashCode 方法以仅包含它来产生这样的行为:

public class Person {
// members, constructors, etc.

@Override
public boolean equals(Object other) {
if (!(other instanceof Person)) {
return false;
}
return name.equals(((Person)other).name);
}

@Override
public int hashCode() {
return name.hashCode();
}
}

关于java - 如何将具有唯一字段的对象添加到 Set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38164179/

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