开发者

LinkedHashSet or ArrayList

I wish to

  1. Avoid duplicated item being inserted.
  2. When I iter开发者_StackOverflow社区ate through the collection class, the returned item is same as insertion order.

May I know, what thing I should consider, to choose either ArrayList (explicitly perform contains check before insertion) or LinkedHashSet?

Thanks.


Definitely use LinkedHashSet. It is made for what you need. Searching entire ArrayList every time you need to insert something will be performance killer (O(n) every time))


Use LinkedHashSet if you don't want duplicate items inserted.


A LinkedHashSet seems to fit the bill perfectly.

When you build your own objects, and plan to use them in a Collection like LinkedHashSet here. Don't forget to override both equals and hashcode for the item you are going to store in it.


Please check this out: http://wiki3.cosc.canterbury.ac.nz/images/e/e9/JavaCollections.png

LinkedHashSet is what you need, because it's an implementation of the Set interface. Set has one very cool habit: it doesn't allows duplicates by default. So, we are done with your 1.

What about 2? We know, that we need one of the Set implementation, but which ?

HashMap - you are able to store K,V pairs, but there is no order.

TreeSet - this is the slowest solution, because it's using a compareTo method to keep every item sorted and ordered. This is why you can pass a comparator to it, when you are constructing a TreeSet.

LinkedHashSet - Gives back the elements in order of INSERTING them. It is the ordered version of a HashSet.

Please find a cool description here: http://java67.blogspot.co.uk/2014/01/when-to-use-linkedhashset-vs-treeset-vs-hashset-java.html?_sm_au_=iVVMtMLHSDQ5P0P7

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜