Looking at this question it made me curious as to which to use, Hashset vs ArrayList. The Hashset seems to have a better lookup and ArrayList has a better insert (for many many objects). So I my question is, since I can't insert using an ArrayList, then search through it using a HashSet, I'm going to have to pick one or the other. Would inserting with an ArrayList, converting to a HashSet to do the lookups, be SLOWER overall than to just insert into a HashSet then lookup? Or just stick with the ArrayList, although the lookup is worse, the inserting makes up for it?
-
1"Would inserting with an ArrayList, converting to a HashSet to do the lookups, be SLOWER overall than to just insert into a HashSet then lookup?" Yes.Jeroen Vannevel– Jeroen Vannevel2013-11-07 15:44:48 +00:00Commented Nov 7, 2013 at 15:44
-
Yeah I figured this was the case, any overall suggestion? ArrayList or Hashset?jp093121– jp0931212013-11-07 15:47:31 +00:00Commented Nov 7, 2013 at 15:47
-
3@jp093121. Apples or oranges? Puppies or cars?Alexander Pogrebnyak– Alexander Pogrebnyak2013-11-07 15:48:40 +00:00Commented Nov 7, 2013 at 15:48
-
Depends on your data.Arash Saidi– Arash Saidi2013-11-07 15:48:46 +00:00Commented Nov 7, 2013 at 15:48
-
1HashSet is NOT a replacement for ArrayList in general. See JavaDoc: docs.oracle.com/javase/7/docs/api/java/util/List.html vs. docs.oracle.com/javase/7/docs/api/java/util/Set.html.isnot2bad– isnot2bad2013-11-07 15:49:36 +00:00Commented Nov 7, 2013 at 15:49
3 Answers
It very much depends on the size of the collection and the way you use it. I.e. you can reuse the same HashSet for copying and this would save you time. Or you can keep them up-to-date.
Creating a HashSet copy for each element lookup will always be slower.
You can also utilize LinkedHashSet which has quick insertion and a HashSet's look up speed at cost of a little worse memory consumption and O(N) index(int) operation.
Comments
You must decide for your specific application which tradeoff pays off better. Do you first insert everything, then spend the rest of the time looking up, maybe occasionally adding a few more? Use HashSet. Do you have a lot of duplicates, which you must suppress? Another strong point for HashSet. Do you insert a lot all the time and only do an occasional lookup? Then use ArrayList. And so on, there are many more combinations and in some cases you'll have to benchmark it to see.