Question

I was asked this question during my interview "How to create Linkedhashset using Hashset ?" anyone knows the answer ?

Was it helpful?

Solution

The LinkedHashSet class has a public LinkedHashSet(Collection<? extends E> c) constructor, so you could do

HashSet<Foo> hs = new HashSet<Foo>();
// add items...
LinkedHashSet<Foo> lhs = new LinkedHashSet<Foo>(hs);

to get a LinkedHashSet instance with the same content as hs. Note that there is no guarantee that the items from hs are inserted into lhs in the same order they were inserted into hs, since that information was never saved by hs.

There is no way to make "an HashSet which behaves like LinkedHashSet", that is, an instance of runtime class HashSet that behaves like a LinkedHashSet instance. However, you could do

HashSet<Foo> hs = new LinkedHashSet<Foo>();

which would give you an instance that would be seen by the outside world as a plain HashSet but use the LinkedHashSet implementation internally. I fail to see why you would ever want to do that, though - you would only gain a bunch of overhead and no added functionality, since the declared type is HashSet. The reason you'd want to use a LinkedHashSet in the first place is to be guaranteed the predictable iteration order, but you still wouldn't be able to assume that for hs - you could assign hs = new HashSet<Foo>() at any time, for instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top