gpt4 book ai didi

java - 检查 arraylist 是否包含具有属性的对象

转载 作者:行者123 更新时间:2023-12-02 12:36:07 27 4
gpt4 key购买 nike

我正在尝试使用一种方法来检查数组列表是否包含具有属性的对象。

public class Network {
// this variable is instantiated and set by the constructor
private ArrayList<Person> persons;

/**
* Constructor for objects of class Network
*/
public Network() {
// initialize instance variables
persons = new ArrayList<>();
persons.add(new Person("name1"));
persons.add(new Person("name2"));
}

这就是我目前所拥有的,但我无法让它工作。

public Person lookupPerson(String personName) {
boolean personContain = persons.contains(new Person(personName));

if (personContain == true) {
System.out.println("ye");
} else {
System.out.println("nah");
}

return null;
}

最佳答案

阅读ArrayList.contains文档。

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

它将使用parameter equals方法,它是在Person中定义的吗?可能不是,所以它将使用 Object.equals 来检查引用,而不是实例内容。

创建类似的方法

class Person {
...
@Override
public boolean equals(Object o){
if(o instanceof Person){
Person p = (Person) o;
return this.name.equals(p.getName());
} else
return false;
}
}

关于java - 检查 arraylist 是否包含具有属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46444855/

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