I was asked this question during my interview "How to create Linkedhashset using Hashset ?" anyone knows the answer ?
-
1Java? And what do you mean by "using Hashset"? – Emil Lundberg Jul 27 '13 at 19:30
-
yes for Java, basically an HashSet which behaves like LinkedHashSet, the order of insertion is preserved. Say, I only have HashSet and want to make it behave like LinkedHashSet. – ACS Jul 28 '13 at 07:07
1 Answers
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.

- 7,268
- 6
- 37
- 53
-
1It's considered good manners to accept an answer that helped you. :) – Emil Lundberg Jul 28 '13 at 20:54