I am creating a List that converts a List of Observations(Registration registration, Time time) into a List containing only Registrations, however this list cannot contain duplicates and I'm battling to ensure that duplicates don't occur.
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;
}
This is what I have got, but duplicates still occur.
With observations such as the following:
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"));
The .equals() method for the Registration class is:
public boolean equals(Registration other){
if (getIdentifier().equals(other.getIdentifier()))
return true;
return false;
}
I would like the output of obsList.getVehicles to be :
[CA 976-543, BCD 123 MP]
But instead I am getting:
[CA 976-543, BCD 123 MP, CA 976-543]
The contains method uses the elements' equals method. For lists, it essentially iterates over all the elements of the list and checks if that element is equal to the value passed.
According to your last comment, you haven't properly overridden it. equals takes an Obejct argument. In fact, instead of overriding the method, you've overloaded it. Using the @Override annotation would have, in fact, caused a compilation error on this method and made the mistake clearer:
@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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With