我有ArrayList
Objects
。我想看看ArrayList
是否包含带有特定字段的Object
。
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;
}
}
我不想使用循环,我不想覆盖arrayList.contains()
。
我希望.contains()
能够遍历我的TeamMember
列表,并在找到等于true
的{{1}}时返回Object
。两个Objects
相等,但.contains()
方法返回false。
如何优雅地检查Team
是否包含具有指定ID的TeamMember
?我的印象是因为Java method: Finding object in array list given a known attribute value我可以避免for循环,但我无法让它工作。
答案 0 :(得分:1)
最优雅的解决方案是
a.equals(b)
然后b.equals(a)
必须为真。hashCode()
,它应该使用与equals方法相同的字段。HashMap<String, TeamMember>
。get(String key)
。