Java HashSet vs Array Performance

后端 未结 5 983
情书的邮戳
情书的邮戳 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:29

    It looks like you will want an HashMap that maps id's to counts. Particularly,

    HashMap counts=new HashMap();
    counts.put(uniqueID,counts.get(uniqueID)+1);
    

    This way, you get amortized O(1) adds, contains and retrievals. Essentially, an array with unique id's associated with each object IS a HashMap. By using the HashMap, you get the added bonus of not having to manage the size of the array, not having to map the keys to an array index yourself AND constant access time.

提交回复
热议问题