Possible Duplicate:
Benefits of arrays
Hey there,
are there any reasons to prefer Arrays (MyObject[])
over ArrayLists (List<MyObject>)
? The only left place to use Arrays is for primitive data types (int, boolean, etc.). However I have no reasonable explanation for this, it just makes the code a little bit slimmer.
In general I use List in order to maintain a better flexibility. But are there reasons left to use real Arrays?
I would like to know, best regards
An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.
Lists can easily grow in size, and you can add and remove elements in the middle of the list easily. That cannot be done with arrays. You need to consider what you need the list for though. If you don't think the list is going to change a lot, then use an array instead.
I prefer to use Array
s over ArrayList
s whenever I know I am only going to work with a fixed number of elements. My reasons are mostly subjective, but I'm listing them here anyway:
Using Collection
classes for primitives is appreciably slower since they have to use autoboxing and wrappers.
I prefer the more straightforward []
syntax for accessing elements over ArrayList
's get()
. This really becomes more important when I need multidimensional arrays.
ArrayList
s usually allocate about twice the memory you need now in advance so that you can append items very fast. So there is wastage if you are never going to add any more items.
(Possibly related to the previous point) I think ArrayList
accesses are slower than plain arrays in general. The ArrayList
implementation uses an underlying array, but all accesses have to go through the get()
, set()
, remove()
, etc. methods which means it goes through more code than a simple array access. But I have not actually tested the difference so I may be wrong.
Having said that, I think the choice actually depends on what you need it for. If you need a fixed number of elements or if you are going to use multiple dimensions, I would suggest a plain array. But if you need a simple random access list and are going to be making a lot of inserts and removals to it, it just makes a lot more sense to use an Arraylist
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