How can I check if an ArrayList contains an Object with a specific field value?

7k views Asked by At

I have an ArrayList of Objects. I want to see if that ArrayList contains an Object with a particular field.

TeamBuilder.java

public class TeamBuilder {

    public static void main(String[] args) {
        Team team = new Team();
        team.addMember(new TeamMember("myID"));
        System.out.println(team.containsMember("myID"));  //false
    }

}

TeamMember.java

public class TeamMember {

    private String id;

    public TeamMember(String id) {
        this.id = id;
    }

    public String getID() {
        return this.id;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof TeamMember) {
            o = ((TeamMember) o).getID();
        }
        return o.equals(this.getID());
    }

}

Team.java

import java.util.ArrayList;

public class Team {

    private ArrayList<TeamMember> members = new ArrayList<>();

    public boolean addMember(TeamMember teamMember) {
        if (members.contains(teamMember)) {
            return false;
        }
        members.add(teamMember);
        return true;
    }

    public boolean containsMember(String eid) {
        System.out.println(members.get(0).equals(eid));  //true
        System.out.println(members.contains(eid));  //false
        if (members.contains(eid)) {
            return true;
        }
        return false;
    }

}

I do not want to use a loop and I do not want to overwrite arrayList.contains().

I was expecting .contains() to iterate through my list of TeamMember's and return true when it found one that was equal to the Object passed. The two Objects are equal, but the .contains() method is returning false.

How can I elegantly check to see if a Team contains a TeamMember with the specified ID? I was under the impression I could avoid a for loop because of Java method: Finding object in array list given a known attribute value, but I am not able to get it to work.

1

There are 1 answers

1
Hovercraft Full Of Eels On BEST ANSWER

The most elegant solution is to

  1. First and foremost fix your equals method so that it fulfills equals contract --- meaning if a.equals(b) then b.equals(a) must be true.
  2. You should never have a TeamMember object be equal to a String. That will result in the possibility of hard to debug side effects and bugs, that you really don't want.
  3. The equals method should never throw an exception. He should first check for reference equality, then class sameness, then field equality.
  4. Your TeamMember class should also override hashCode() and it should use the same fields as the equals method does.
  5. then set up a HashMap<String, TeamMember> that matches ID Strings TeamMember objects.
  6. Be sure that your ID's are immutable.
  7. Fill your Map with String-TeamMember pairs
  8. Call get(String key) when you need a TeamMember that matches an ID.