Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if arraylist contains an object with an attribute [duplicate]

Tags:

java

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;
}
like image 258
Awaythrows8 Avatar asked Sep 15 '25 11:09

Awaythrows8


1 Answers

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;
     }
}
like image 60
AxelH Avatar answered Sep 17 '25 02:09

AxelH