javaarraylistcollectionshashsetlinkedhashset

Can LinkedHashSet in this code be replaced with a HashSet?


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));
    }
}

Solution

  • 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)