我正在创建一个List,它将观察列表(注册注册,时间)转换为仅包含注册的列表,但是这个列表不能包含重复项,我正在努力确保不会发生重复.
public List<Registration> getVehicles(){
List<Registration> rtnList = new ArrayList<Registration>();
for (Observation obs:observationsList){
if (rtnList.contains(obs.getIdentifier())){
}
else
rtnList.add(obs.getIdentifier());
}
return rtnList;
}
Run Code Online (Sandbox Code Playgroud)
这就是我所拥有的,但仍然会出现重复.
通过以下观察:
obsList.record (new Registration("CA 976-543"), new Time("13:15:03"));
obsList.record (new Registration("BCD 123 MP"), new Time("13:21:47"));
obsList.record (new Registration("CA 976-543"), new Time("13:35:50"));
Run Code Online (Sandbox Code Playgroud)
Registration类的.equals()方法是:
public boolean equals(Registration other){
if (getIdentifier().equals(other.getIdentifier()))
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
我想obsList.getVehicles的输出是:
[CA 976-543,BCD 123 MP]
但相反,我得到:
[CA 976-543,BCD 123 MP,CA 976-543]
该contains方法使用元素的equals方法.对于列表,它基本上遍历列表的所有元素,并检查该元素是否等于传递的值.
根据您的上一条评论,您没有正确覆盖它.equals采取Obejct争论.事实上,而不是覆盖的方法,你已经超负荷了.@Override实际上,使用注释会导致此方法出现编译错误,并使错误更加清晰:
@Override
public boolean equals(Object o) { // Note the argument type
if (!(o instanceof Registration)) {
return false;
}
Registration other = (Registration) o;
return getIdentifier().equals(other.getIdentifier()) &&
getProvince().equals(other.getProvince());
}
Run Code Online (Sandbox Code Playgroud)