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?
which concrete class should I choose?
I would probably just go with an ArrayList
or a LinkedList
. Both support the add
and iterator
methods, and neighter of them have any considerable overhead.
Is there any advantage to using a Set rather than a List, for example?
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.)
Which one would have the least overhead?
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 :-)
Do not go with a Set
. Sets and Lists differ according to their purpose, that you should always consider when choosing the right Collection
List
is there for maintaining elements in the order you added them; and if you insert the same element twice it will be kept twiceSet
is there for holding one specific element exactly once (uniqueness); order is only relevant for specific implementations (like TreeSet
), but still elements that are 'the same' would not be added twiceSet
is only meaningful if you want to sort your objects and to make sure no duplicate element is 'registered'. Else, an ArrayList
is just fine.
However, if you want to add elements while iterating too, an ArrayBlockingQueue
is better.
Here are some key points which can help you to choose your collection according to your requirement -
List(ArrayList or LinkedList)
Set
So according to your requirement List seems to be a suitable choice.
Now Between ArrayList and LinkedList -
ArrayList is a random access list. Use if your frequent operation is the retrieval of elements.
LinkedList is the best option if you want to add or remove elements from the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With