Can the LinkedHashSet in this code replace with a HashSet?

What does the following code do? Is it possible to replace LinkedHashSetwith HashSet?

public class CollectionFunction {
    public <E> List<E> function(List<E> list) {
        return new ArrayList<E>(new LinkedHashSet<E>(list));
    }
}
+3
source share
4 answers

What does the following code do?

It seems to be used to remove duplicates from a list without changing the order

  • deletes duplicates (LinkedHashSet is a collection)
  • supports insertion order ( LinkedHashSet has a predictable iteration order)
  • convert back to list

Can I replace LinkedHashSet with a HashSet?

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

+7
source

A Set - , . HashSet , . - .

+1

.

a,b,c,d,a , a,b,c,d .

,

LinkedHashSet HashSet, .

, b,c,d,a, LinkedhashSet HashSet

+1

It creates an ArrayList from an object that implements the List interface. The ArrayList class has a constructor that accepts a collection: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html You should look if also HashSet implements Collection http://docs.oracle .com / javase / 7 / docs / api / java / util / Collection.html . You should also look if HashSet provides the appropriate constructor. Since the HashSet fulfills both requirements, you can replace it :-).

-3
source

All Articles