Search code examples
androidarraylistunique

Unique values in my ArrayList


I have next class:

private class LocoList{
    String Id;
    String Name;
    String Latitude;
    String Longitude;

    LocoList(String LocationId, String LocationName,  String 
        LocationLatitude, String LocationLongitude){

        this.Id = LocationId;
        this.Name = LocationName;
        this.Latitude = LocationLatitude;
        this.Longitude = LocationLongitude;
        }

    @Override public boolean equals(Object obj) {
        if (obj == this) { return true; }
        if (obj == null || obj.getClass() != this.getClass()) { return false; }
        NearLocoList guest = (NearLocoList) obj;
        return Id == guest.Id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(Id);
    }

}

to use with next array:

private ArrayList<LocoList> myLocations = new ArrayList<>();

To populate my arrayList I use next method:

private void getLocoDatabase(LatLng PoI) {

    double mLatitude, mLongitude;
    mLatitude = PoI.latitude;
    mLongitude = PoI.longitude;

    ArrayList<ArrayList<Object>> dataLocation =
            mDBhelperMA.getLocations(mLatitude, mLongitude);

   for (int i = 0; i < dataLocation.size(); i++) {
        ArrayList<Object> row = dataLocation.get(i);

  if (!myLocations.contains(new LocoList(row.get(0).toString(), row.get(1).toString(), row.get(2).toString(),row.get(3).toString) {
        myLocations.add(new LocoList(row.get(0).toString(), row.get(1).toString(), row.get(2).toString(),row.get(3).toString);
        }
    }
}

My problem is that need to call GetLocoDatabase couple times for different LatLng and want to avoid duplicated values.

What I must to do to can have on myLocations ArrayList just unique values? Want to avoid to have same location twice or more.


Solution

  • You have to do two things:

    • override the default equals()/hashCode() implementaiton
    • change from using a List/ArrayList to a Set/HashSet for example

    You have to understand that different collection classes have different properties. When "uniqueness" is your primary concern, then use sets, not lists.