我有一个java.util.Set<City> cities
,我需要通过两种方式将城市添加到这个集合中:
cities.add(city)
方法调用)cities.addAll(anotherCitiesSet)
方法调用)但第二种方法的问题是,我不知道anotherCitiesSet
中是否有重复的城市。
每当尝试在cities
集合中输入重复条目时,我都想做一些处理。
发布于 2010-04-16 20:39:52
复制cities
集(也就是citiesCopy
),然后调用citiesCopy.retainAll(anotherCitiesSet)
- citiesCopy
中的结果集将包含两个集的交集,从而允许您轻松地查看哪些城市是重复的。
或者,遍历第二个集合并手动添加每个元素,每次检查add()
的返回值:
for(java.util.Set<City> c : anotherCitiesSet) {
if(!cities.add(c)) {
// c was a duplicate, do something?
}
}
发布于 2010-04-16 20:39:48
从java.util.Set派生一个类,如果可能,覆盖addAll (如果不是,则创建新方法),然后逐个添加项,如果检测到重复条目,则执行自定义处理。
发布于 2018-05-30 06:53:01
你的城市是字符串(尽管它是对象)还是包含其他东西的对象?
因为你可能有两个城市:纽约市和另一个纽约市。包含相同的信息。但因为它们是堆中的两个对象。它们将具有不同的HashCode。上面写着,您的HashSet将保留这两个文件。HashSet同时检查HashCode和meaning ()。
解决方案是覆盖这两个方法:
class City{
String name; //if you only care city name
....
....
public boolean equals(Object myCity){ // override equals(). only look at the name.
City city2 = (City) myCity;
return this.getName().equals(city2.getName()); //String itself has a .equal() to compare
}
public int HashCode(){ // override HashCode().
return name.hashCode(); //also String itself has a .hashCode() to check equality
}
public String getName(){
return name;
}
...
...
}
https://stackoverflow.com/questions/2652932
复制相似问题