If I am going to create a Java Collection, and only want to fill it with elements, and then iterate through it (without knowing the necessary size beforehand), i.e. all I need is Collection<E>.add(E) and Collection<E>.iterator(), which concrete class should I choose? Is there any advantage to using a Set rather than a List, for example? Which one would have the least overhead?
If I am going to create a Java Collection, and only want to fill
Share
I would probably just go with an
ArrayListor aLinkedList. Both support theaddanditeratormethods, and neighter of them have any considerable overhead.No, I wouldn’t say so. (Unless you rely on the order of the elements, in which case you must use a List, or want to disallow duplicates, in which case you should use a Set.)
(I don’t see how any Set implementation could beat a list implementation for add / iterator methods, so I’d probably go with a List even if I don’t care about order.)
Sounds like micro benchmarking here, but if I’d be forced to guess, I’d say ArrayList (or perhaps LinkedList in coner cases where ArrayLists need to reallocate memory often 🙂