我正在编写一段代码,它需要大量对象并将它们添加到另一个数组中。问题是,我不想要任何重复的。有没有办法实现哈希集来解决这个问题?
public static Statistic[] combineStatistics(Statistic[] rptData, Statistic[] dbsData) {
HashSet<Statistic> set = new HashSet<Statistic>();
for (int i=0; i<rptData.length; i++) {
set.add(rptData[i]);
}
/*If there's no data in the database, we don't have anything to add to the new array*/
if (dbsData!=null) {
for (int j=0; j<dbsData.length;j++) {
set.add(dbsData[j]);
}
}
Statistic[] total=set.toArray(new Statistic[0]);
for (int workDummy=0; workDummy<total.length; workDummy++) {
System.out.println(total[workDummy].serialName);
}
return total;
}//end combineStatistics()
最佳答案
如果您希望值相等而不是引用相等,请在 YourObject
上正确实现 equals(Object obj)
和 hashCode()
。
Set<YourObject> set = new HashSet<YourObject>(yourCollection);
或
Set<YourObject> set = new HashSet<YourObject>();
set.add(...);
然后
YourObject[] array = set.toArray(new YourObject[0])
关于java - 哈希集对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20431521/