gpt4 book ai didi

java - 将人员添加到 ArrayList 中,除非他们已经在列表中(名字和姓氏字符串)

转载 作者:行者123 更新时间:2023-11-30 02:35:22 26 4
gpt4 key购买 nike

我需要将 Person p 添加到联系人 ArrayList 中,除非它包含相同的姓氏和名字。

在这种情况下,我需要返回错误消息“无法添加人员”。这是我当前的代码:

public class AddressBook {
private ArrayList<Person> contacts;
public AddressBook(){
this.contacts = new ArrayList<Person>();
}

public void addPerson(Person p) {
for (int i = 0; i < contacts.size(); i++) {
if(contacts.get(i).getfirstName().equals(p.firstName)){
System.out.printf("could not add person");
}
}
this.contacts.add(p);
}

我无法弄清楚应该如何比较要通过 addPerson() 添加的字符串方法,其中包含已包含在列表中的 Person 对象中的现有字符串。

最佳答案

我认为您不应该使用List来执行此操作。如果您想要一个拒绝重复的集合,您应该使用Set

所以在我看来你应该用这样的东西改变你的代码:

public class AddressBook {

// You have to use a LinkedHashSet instead of a HashSet if you want to keep order
private Set<Person> contacts = new HashSet<>();

// v1 : add p only if not present in contacts and don't log anything
public void addPerson(Person p) {
contacts.add(p);
}

// v2 : log if duplicate
public void addPerson(Person p) {
if(contacts.contains(p))
System.out.println("Duplicate here");
else
contacts.add(p);
}

// If you really need an List (maybe to be compatible with an API ?)
public List<Person> asList() {
return new ArrayList<>(contacts);
}
}

要使用此代码,您必须在 Person 类中实现 hashCodeequals 方法。但我认为这是一个更好的方法。

关于java - 将人员添加到 ArrayList 中,除非他们已经在列表中(名字和姓氏字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43248827/

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