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

前端 未结 7 1601
忘掉有多难
忘掉有多难 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:04

    Be sure to read my comment about TreeSet at the bottom if you choose to implement B)

    If your app only does occasional sorts but iterates through it a lot, I'd say you're best off using a straightforward unsorted list. Sort it the once and then benefit from faster iteration. Iteration is especially fast on an array list.

    However if you want sort order to be guaranteed all of the time or you are possibly adding / removing elements frequently then use a sorted collection and take the hit on iteration.

    So in your case I would say A) is the better option. The list is sorted once, doesn't change and therefore benefits from being an array. Iteration should be very fast, especially if you know its an ArrayList and can directly use the ArrayList.get() instead of an Iterator.

    I'd also add that TreeSet by definition is a Set which means objects are unique. A TreeSet determines equality by using compareTo on your Comparator / Comparable. You could easily find yourself missing data if you try to add two objects whose compareTo returns a value of 0. e.g. adding "C", "A", "B", "A" to a TreeSet will return "A", "B", "C"

提交回复
热议问题