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.
The most elegant solution is to
a.equals(b)
thenb.equals(a)
must be true.hashCode()
and it should use the same fields as the equals method does.HashMap<String, TeamMember>
that matches ID Strings TeamMember objects.get(String key)
when you need a TeamMember that matches an ID.