Java collection insertion: Set vs. List

后端 未结 7 886
花落未央
花落未央 2021-02-14 10:56

I\'m thinking about filling a collection with a large amount of unique objects. How is the cost of an insert in a Set (say HashSet) compared to an List (say ArrayList)?

7条回答
  •  时光说笑
    2021-02-14 11:32

    I don't think you can make this judgement simply on the cost of building the collection. Other things that you need to take into account are:

    • Is the input dataset ordered? Is there a requirement that the output data structure preserves insertion order?
    • Is there a requirement that the output data structure is ordered (or reordered) based on element values?
    • Will the output data structure be subsequently modified? How?
    • Is there a requirement that the output data structure is duplicate free if other elements are added subsequently?
    • Do you know how many elements are likely to be in the input dataset?
    • Can you measure the size of the input dataset? (Or is it provided via an iterator?)
    • Does space utilization matter?

    These can all effect your choice of data structure.

提交回复
热议问题