这是一个完整的例子:
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class GeoName {
private String country, city;
private float lat, lon;
public GeoName(String country, String city, float lat, float lon){
this.country = country;
this.city = city;
this.lat = lat;
this.lon = lon;
}
@Override
public boolean equals(Object other){
if(other==null) return false;
if(other instanceof GeoName){
return ((GeoName)other).city.equals(this.city) &&
((GeoName)other).country.equals(this.country);
}
return false;
}
@Override
public String toString(){
return city + ", "+ country +
", " + lat +", " + lon;
}
@Override
public int hashCode(){
return Objects.hash(country, city);
}
public static void main(String[] args) {
List<GeoName> list = new ArrayList<>();
list.add(new GeoName("Madrid", "Spain",1.0f, 2.0f));
list.add(new GeoName("England", "London",3.0f, 4.0f));
list.add(new GeoName("England", "London",3.0f, 4.0f));
list.add(new GeoName("France", "Paris",7.0f, 9.0f));
list.add(new GeoName("Mexico", "Madrid",9.0f, 10.0f));
Set<GeoName> set = new HashSet<>(list);
for(GeoName geoName : set){
System.out.println(geoName);
}
}
}
输出:
London, England, 3.0, 4.0
Madrid, Mexico, 9.0, 10.0
Paris, France, 7.0, 9.0
Spain, Madrid, 1.0, 2.0
Set
集合;你只需要重写Object#equals
方法,不考虑经纬度即可。 - Jacob G.