Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there reasons to prefer Arrays over ArrayLists? [duplicate]

Tags:

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

like image 703
BrokenClockwork Avatar asked Jan 30 '11 12:01

BrokenClockwork


People also ask

Why is array preferred over ArrayList?

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.

What are the main reasons for choosing to use a list instead of an array?

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.


1 Answers

I prefer to use Arrays over ArrayLists 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:

  1. Using Collection classes for primitives is appreciably slower since they have to use autoboxing and wrappers.

  2. I prefer the more straightforward [] syntax for accessing elements over ArrayList's get(). This really becomes more important when I need multidimensional arrays.

  3. ArrayLists 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.

  4. (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

like image 69
MAK Avatar answered Oct 04 '22 16:10

MAK