문제

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