24

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

Community
  • 1
  • 1
BrokenClockwork
  • 241
  • 1
  • 2
  • 3
  • 1
    possible duplicate of [Benefits of arrays](http://stackoverflow.com/questions/2843928/benefits-of-arrays). In general, you will already find a lot of ArrayList vs Array questions here. – Felix Kling Jan 30 '11 at 12:34
  • why don't you merge and delete this one? – bestsss Jan 30 '11 at 16:43

4 Answers4

21

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

MAK
  • 26,140
  • 11
  • 55
  • 86
1

Generally arrays have their problems, e.g. type safety:

Integer[] ints = new Integer[10];
Number[] nums = ints; //that shouldn't be allowed
nums[3] = Double.valueOf[3.14]; //Ouch!

They don't play well with collections, either. So generelly you should prefer Collections over arrays. There are just a few things where arrays may be more convenient. As you already say primitive types would be a reason (although you could consider using collection-like libs like Trove). If the array is hidden in an object and doesn't need to change its size, it's OK to use arrays, especially if you need all performance you can get (say 3D and 4D Vectors and Matrices for 3D graphics). Another reason for using arrays may be if your API has lots of varargs methods.

BTW: There is a cute trick using an array if you need mutable variables for anonymous classes:

public void f() {
   final int[] a = new int[1];
   new Thread(new Runnable() {
      public void run() {
         while(true) {
            System.out.println(a[0]++);
         }
      }    
   }).start();  
}

Note that you can't replace the array with an int variable, as it must be (effectively) final.

Community
  • 1
  • 1
Landei
  • 54,104
  • 13
  • 100
  • 195
0

one for you:

sorting List (via j.u.Collections) are first transformed to [], then sorted (which clones the [] once again for the merge sort) and then put back to List. You do understand that ArrayList has a backing Object[] under the cover.

Back in the day there was a case ArrayList.get was not inlined by -client hotspot compiler but now I think that's fixed. Thus, performance issue using ArrayList compared to Object[] is not so tough, the case cast to the appropriate type still costs a few clocks (but it should be 99.99% of the times predicted by the CPU); accessing the elements of the ArrayList may cost one more cache-miss more and so (or the 1st access mostly)

So it does depend what you do w/ your code in the end.

Edit Forgot you can have atomic access to the elements of the array (i.e. CAS stuff), one impl is j.u.c.atomic.AtomicReferenceArray. It's not the most practical ones since it doesn't allow CAS of Objec[][] but Unsafe comes to the rescue.

bestsss
  • 11,796
  • 3
  • 53
  • 63
0

I think that the main difference of an array and a list is, that an array has a fixed length. Once it's full, it's full. ArrayLists have a flexible length and do use arrays to be implemented. When the arrayList is out of capacity, the data gets copied to another array with a larger capacity (that's what I was taught once).

An array can still be used, if you have your data length fixed. Because arrays are pretty primitive, they don't have much methods to call and all. The advantage of using these arrays is not so big anymore, because the arrayLists are just good wrappers for what you want in Java or any other language.

I think you can even set a fixed capacity to arraylists nowadays, so even that advantage collapses.

So is there any reason to prefer them? No probably not, but it does make sure that you have just a little more space in your memory, because of the basic functionality. The arraylist is a pretty big wrapper and has a lot of flexibility, what you do not always want.

Marnix
  • 6,384
  • 4
  • 43
  • 78
  • >"The arraylist is a pretty big wrapper and has a lot of flexibility, what you do not always want.?< This not true (big wrapper part, it's a thin one actually) unless there is a **lot** of extra unused space. – bestsss Jan 30 '11 at 12:46
  • @bestsss ArrayLists create arrays that have extra capacity. So yes, there is extra space used, which was maybe not needed in the first place. Depending on the type of objects you put into the arraylist, the arraylist becomes larger by the extra capacity. – Marnix Jan 30 '11 at 12:48
  • >Depending on the type of objects you put into the arraylist, the arraylist becomes larger by the extra capacity< not true either, the extra space represents references only (i.e. 4/8 bytes on 32/64). Plus, you can always use trimToSize() if you want to have the exactly memory (plus one int (4/8bytes) and one object header more ~24bytes or so) allocated as Object[]. Here is a link: http://stackoverflow.com/questions/4739947/what-is-the-memory-size-of-a-arraylist-in-java/4739986#4739986 – bestsss Jan 30 '11 at 12:53