Is it faster to add to a collection then sort it, or add to a sorted collection?

前端 未结 7 1578
忘掉有多难
忘掉有多难 2020-11-28 04:36

If I have a Map like this:

HashMap map;

and I want to obtain a collection of values sorted us

相关标签:
7条回答
  • 2020-11-28 05:13

    TreeSet has a log(n) time complexity guarantuee for add()/remove()/contains() methods. Sorting an ArrayList takes n*log(n) operations, but add()/get() takes only 1 operation.

    So if you're mainly retrieving, and don't sort often, ArrayList is the better choice. If you sort often but dont retrieve that much TreeSet would be a better choice.

    0 讨论(0)
提交回复
热议问题