I'm trying to use a method to check if an arraylist contains an object with an attribute.
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"));
}
This is what i have at the moment, but i cant get it to work.
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;
}
Read ArrayList.contains
doc.
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)).
It will use the parameter equals
method, is it defined in Person
? Probably not so it will use Object.equals
that will check the references, not instance content.
Create the method like
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With