I'm writing a piece of code which takes a great deal of objects and adds them to another array. The catch is, I don't want any duplicates. Is there a way I could implement a Hashset to solve this problem?

    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()
有帮助吗?

解决方案

Properly implement equals(Object obj) and hashCode() on YourObject if you expect value equality instead of reference equality.

Set<YourObject> set = new HashSet<YourObject>(yourCollection);

or

Set<YourObject> set = new HashSet<YourObject>();
set.add(...);

then

YourObject[] array = set.toArray(new YourObject[0])

其他提示

I think you should pay attention to:

1 - what to do if there is a duplicate in the original Collection? Use the first added to the array? Use the other(s)?

2 - You definitely need to implement equals and hashcode so that you can tell what are duplicate objects

3 - Are you going to create a fixed size array and then won't add anymore objects? Or are you going to keep adding stuff?

You can use any kind of Set actually, but if you use LinkedHashSet, then you will have a defined iteration order (which looks like an array). HashSet wont't garantee any order and TreeSet will try to order data ascending.

Depends on what you are referring to as a duplicate. If you mean an identical object, then you could use a List and simply see if the List contains the object prior to adding it to the list.

Object obj = new Object();
List<Object> list = new ArrayList<Object>();

if (!list.contains(obj)) {
    list.add(obj);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top