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));
}
}
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));
}
}
What does the following code do?
It seems like it is used to remove duplicates from a list without changing the order
Can the LinkedHashSet be replaced with a HashSet?
No, it will not keep the order guaranteed (#2)
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.
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
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 :-).