0

I found an algorithm containing a merge method (https://commons.apache.org/proper/commons-math/jacoco/org.apache.commons.math3.stat.clustering/DBSCANClusterer.java.html)

private <T> List<T> theirMerge(final List<T> one, final List<T> two) {
    final Set<T> oneSet = new HashSet<T>(one);
    for (T item : two) {
        if (!oneSet.contains(item)) {
            one.add(item);
        }
    }
    return one;
}

What is the main benefit of using a HashSet here?

My simpler implementation looks like this

private <T> List<T>  myMerge (ArrayList<T> one, ArrayList<T> two){
    for (T item: two) {
        if(!one.contains(item)){
            one.add(item);
        }
    }
    return one;
}
froehli
  • 904
  • 1
  • 11
  • 35
  • 3
    Dupe of: http://stackoverflow.com/questions/1035008/what-is-the-difference-between-set-and-list – Tunaki Jan 10 '16 at 16:10
  • I know the difference. But why would I prefere to use the above version? Just to mix up the order? – froehli Jan 10 '16 at 16:13
  • 1
    because of performance (if order is not important), see http://stackoverflow.com/questions/18706870/java-hashset-vs-array-performance – wero Jan 10 '16 at 16:14

1 Answers1

0

You should avoid loops and use addAll method to merge two set and avoid duplicates like:

oneSet.addAll(two);

While in list you are explicitly checking whether don't have an element in list and then only you are adding to the second list.

SMA
  • 36,381
  • 8
  • 49
  • 73
  • You mean creating two sets out of the lists, then calling addAll and then transforming it back to a list? – froehli Jan 10 '16 at 16:19
  • You already created `oneSet`, so add all elements from `two` to it and return that (or create another list of you want to return list). – SMA Jan 10 '16 at 16:22