Java collection insertion: Set vs. List

后端 未结 7 896
花落未央
花落未央 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:34

    There is no "duplicate elimination" such as comparing to all existing elements. If you insert into hash set, it's really a dictionary of items by hash code. There's no duplicate checking unless there already are items with the same hash code. Given a reasonable (well-distributed) hash function, it's not that bad.

    As Will has noted, because of the dictionary structure HashSet is probably a bit slower than an ArrayList (unless you want to insert "between" existing elements). It also is a bit larger. I'm not sure that's a significant difference though.

提交回复
热议问题