开发者

Why we use ArrayList when we could have used Set for adding unique values?

开发者 https://www.devze.com 2023-02-28 19:00 出处:网络
I found an efficient code for adding unique items using the below approach: int[] values = { -5, -3, -1, 0, 3, 6 };

I found an efficient code for adding unique items using the below approach:

int[] values = { -5, -3, -1, 0, 3, 6 };

List<Integer> list=new ArrayList<Integer>();

for(int val : values)

{

   if(!list.contains(val))

   list.add(val);

}

I could have done the same开发者_StackOverflow中文版 work using a HashSet instead of using an ArrayList. That would have helped me by not worring to check if the value already existed in the list. Why is using a Hashset not an efficient approach?


A HashSet does not implement the List interface. And the values in a Set are not indexed. We can't get value from a Set.

So if you just need a storage for unique values, then you can safely use a Set implementation. If you need to keep insertion order or if you need any other functionality of List implementations and uniqueness, then use the method from your question: decorate an existing List implementation and add functionality to reject duplicates.

You asked about efficiency: ArrayList is backed by an array and pretty fast. But the time complexity for contains() is O(n) - to iterate we have look at each and every element in worst case.

HashSet is more or less a decorator of a full blown HashMap, somewhat heavier compared to an array. But the time complexity for contains is O(1) - the check is done in constant time, regardless how many items are inside the map.

If you just want to iterate - a specialized List implementation should be slightly faster - both have a time complexity of O(n) for the iteration (no surprise) but reading from an array is easier then reading from a Map.


Actually, HashSet is a much better approach than ArrayList. Your code runs in O(n) for HashSet, and O(n²) for ArrayList.

But, one thing to keep in mind: elements in HashSet are not kept in any particular order. If you want to keep order and have fast lookups, use LinkedHashSet. (Everything has a cost, though; in this case, LinkedHashSet uses more memory than HashSet.)


It is. The premise to your question is flawed.

Use guava and it's easier:

Set set = Sets.newTreeSet( values ); //or HashSet

0

精彩评论

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

关注公众号