Why do some collection data structures not maintain the order of insertion? What is the special thing achieved compared to maintaining order of insertion? Do we gain someth
Why is it necessary to maintain the order of insertion? If you use HashMap
, you can get the entry by key
. It does not mean it does not provide classes that do what you want.
Theres's a section in the O'Reilly Java Cookbook called "Avoiding the urge to sort" The question you should be asking is actually the opposite of your original question ... "Do we gain something by sorting?" It take a lot of effort to sort and maintain that order. Sure sorting is easy but it usually doesn't scale in most programs. If you're going to be handling thousands or tens of thousands of requests (insrt,del,get,etc) per second whether not you're using a sorted or non sorted data structure is seriously going to matter.
Okay ... so these posts are old as compared to now, but insertion order is needed depending on your need or application requirements, so just use the right type of collection. For most part, it is not needed, but in a situation where you need to utilize objects in the order they were stored, I see a definite need. I think order matters when you are creating for instance a wizard or a flow engine or something of that nature where you need to go from state to state or something. In that sense you can read off stuff from the list without having it keep track of what you need next or traverse a list to find what you want. It does help with performance in that sense. It does matter or else these collections would not make much sense.
I can't cite a reference, but by design the List
and Set
implementations of the Collection
interface are basically extendable Array
s. As Collections
by default offer methods to dynamically add and remove elements at any point -- which Array
s don't -- insertion order might not be preserved.
Thus, as there are more methods for content manipulation, there is a need for special implementations that do preserve order.
Another point is performance, as the most well performing Collection
might not be that, which preserves its insertion order. I'm however not sure, how exactly Collections
manage their content for performance increases.
So, in short, the two major reasons I can think of why there are order-preserving Collection
implementations are: