Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using contains method to avoid duplicates

Tags:

java

list

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]

like image 915
Michelle Lopes Avatar asked Nov 22 '25 12:11

Michelle Lopes


1 Answers

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());    
}
like image 200
Mureinik Avatar answered Nov 25 '25 01:11

Mureinik