Friday, June 8, 2007

There's something fundamentally weird about LinkedHashSet, isn't there?

You use it when you want to have a guaranteed order of iteration (insertion order or LRU order). Except, what would happen if you took your LinkedHashSet and, say, stored it into a HashSet? Later you'd be iterating through the elements of this greater set, and "your" LinkedHashSet will be there, but it might have a completely different iteration order! It might even suddenly be an LRU-ordered set while your original one was insertion-ordered. You'll have no idea what to expect.

So you wanted the iteration order to be respected, and you thought LHS would give you that. But it wasn't respected; it was just discarded.

So... a little bit strange. Just a little.

2 comments:

Unknown said...

Kevin, I'm confused by this. I posted some code snippets at http://stuffthathappens.com/blog/2007/06/08/i-dont-think-linkedhashset-is-weird/

Can you clarify what you mean?

Brian Slesinsky said...

I'm guessing that you mean that if you put two LinkedHashSets with the same elements but different orders into another HashSet, you have no idea what order it will be in when you get it later?