Java HashSet vs Array Performance

后端 未结 5 1017
情书的邮戳
情书的邮戳 2020-12-30 07:50

I have a collection of objects that are guaranteed to be distinct (in particular, indexed by a unique integer ID). I also know exactly how many of them there are (and the n

5条回答
  •  余生分开走
    2020-12-30 08:26

    Depends on your data;

    HashSet gives you an O(1) contains() method but doesn't preserve order.

    ArrayList contains() is O(n) but you can control the order of the entries.

    Array if you need to insert anything in between, worst case can be O(n), since you will have to move the data down and make room for the insertion. In Set, you can directly use SortedSet which too has O(n) too but with flexible operations.

    I believe Set is more flexible.

提交回复
热议问题