3

What does the following code do? Can the LinkedHashSet be replaced with a HashSet?

public class CollectionFunction {
    public <E> List<E> function(List<E> list) {
        return new ArrayList<E>(new LinkedHashSet<E>(list));
    }
}
David Harkness
  • 35,992
  • 10
  • 112
  • 134
sam
  • 95
  • 1
  • 8
  • possible duplicate of [HashSet vs LinkedHashSet](http://stackoverflow.com/questions/5080612/hashset-vs-linkedhashset) – paulsm4 May 10 '12 at 06:57
  • 4
    I wouldn't say that this is a duplicate. – aioobe May 10 '12 at 07:02
  • 1
    Sam, welcome to SO. If you found any of the answers as what you were looking for, you can select them as accepted to mark the question as answered – Eran Medan May 10 '12 at 18:49

4 Answers4

7

What does the following code do?

It seems like it is used to remove duplicates from a list without changing the order

  1. removes duplicates (LinkedHashSet is a Set)
  2. maintains insertion order (LinkedHashSet has predictable iteration order)
  3. convert back to a List

Can the LinkedHashSet be replaced with a HashSet?

No, it will not keep the order guaranteed (#2)

Eran Medan
  • 44,555
  • 61
  • 184
  • 276
1

A Set is an unordered collection of items, where a list must retain the order of the included items. You cannot use a set like HashSet to implement a list, because the order of the items isn't stored. A linked hash set stores these information.

Matten
  • 17,365
  • 2
  • 42
  • 64
1

This function is removing the duplicate elements and keeping the insertion order.

if you give a,b,c,d,a as input you will get a,b,c,d as output.

Yes you can

replace LinkedHashSet with HashSet if you do not want the insertion order.

Output may be like this b,c,d,a if replace LinkedhashSet with HashSet

Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40
-3

It creates an ArrayList out of an object implementing the List interface. The ArrayList class has an constructer which takes a Collection: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html You have to lookup if also the HashSet implements Collection http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html. You also have to lookup if the HashSet provides the according constructer. As the HashSet fulfills both requirements you can replace it :-).

Florian
  • 388
  • 2
  • 3
  • 13