Java: Sorted collection which allows duplicates, is memory efficient and provides fast insert + update

前端 未结 6 1121
野的像风
野的像风 2020-12-15 05:11

Specifically I need a collection which uses one field A for accessing and a different one (field S) for sorting but a sorted collection which accepts duplicate would be suff

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 05:44

    When you need a sorted collection, you should analyze your needs carefully.
    If the majority of operations is inserting and only a few are to search then using a sorted collection i.e. keep the elements sorted in the collection constantly, would not be a good option (due to the overhead of keeping the elements sorted on insert which would be the most common operation).
    In this case it would be best to keep an unsorted collection and do the sorting only when needed. I.e. before the search. You could even use a simple List and sort it (using Collections.sort i.e. mergesort) when needed. But I recommend this with caution, as for this to be efficient the assumption is that you work on large data. In really small data even linear search is good enough.

    If the majority of operations is searching then you could use a sorted collection which from my of point of view there are data structures to choose from (some you already mention) and you could benchmark to see which one fits your needs.

提交回复
热议问题