views:

360

answers:

9
+12  Q: 

Benefits of arrays

As I see it, the advantages of a list over an array are pretty obvious:

  • Generics provide more precise typing: List<Integer>, List<? extends Number>, List<? super Integer>.
  • A List interface has a bunch useful methods: addAll, remove etc. While for arrays all standard operations except get/set must be performed in a procedure manner by passing it to a static method.
  • Collections offer different implementations like ArrayList, LinkedList, unmodifieable and synchronized lists, which can be hidden under a common List interface.
  • OOB length control.

As disadvantages I can only mention the absence of syntactic sugar and a runtime type check. At the same time supporting of both structures requires frequent using of asList and toArray methods, which makes code less readable. So I am curious if there are any important benefits of using arrays that I miss.

+4  A: 

Speed. Collections are somewhat slower than simple arrays: internally most still use arrays, but have additional layers of code around those. Of course, unless you have specific need for extra performance, you should still use collections.

Another smallish advantage of arrays is that it might be easier to call variadic methods with arrays. This should never be a main reason to pick one over another though.

doublep
+9  A: 

If your list does not change often, Lists add lots of extra weight to the object that you will never use. When you are trying to run something that needs to be optimized, this is helpful. This extra weight also makes things slower than they would be with just arrays. However, unless you know that you need the gains arrays give you, you should just be using Lists.

unholysampler
I guess this could be summarized as the following: When you need to manipulate a group of distinctly related objects, use collections, otherwise use arrays.
Esko
+2  A: 

I guess the theoretical answer is that array are supposed to have better performance because Generic collections have additional layers of abstraction. Personally, in a business app, I see very little value in using Arrays over generic collections.

Doobi
+4  A: 

One thing I have not seen mentioned here: arrays can have N dimensions whereas lists are limited to one. You can use lists of lists but the syntax (List<List<...>>) is much more cumbersome than [][]

Guillaume
+1  A: 

Arrays are better in the following situations:

  • you know that you will work with fixed number of elements in the array
  • you don't need to change size of the array

Arrays are:

  • faster than any Collection

Collections similar to Array:

  • ArrayList - fast read and add to the end of the List. Uses internally array. Slow if you have to increase the size of the List
  • LinkedList - fast add to both sides of the List. Fast dynamic size increase/decrease. Doesn't use internally array

Conclusion:

I recommend to use the appropriate for your scenario Collection. Don't struggle with Array [] because the Collections package offers very comfortable API like add(), addAll() etc.


Reference: You can find a more detailed comparison here -> "Arrays vs ArrayList vs LinkedList vs..."

Leni Kirilov
A: 

In addition to the other responses, there is one subtle property of arrays that can be considered an advantage over lists. It can be illustrated by the following code:

//This works
Integer[] ints = new Integer[4];
Number[] nums = ints;
//This doesn't work
List<Integer> intList = new ArrayList<Integer>();
List<Number> numList = intList; //Does not compile
List<Number> numList2 = (List<Number>)intList; //Does not compile either

While an array of a subclass IS an array of the superclass, lists of subclasses are NOT lists of superclasses (and there is a good reason for it - generics would have a type safery flaw if it were allowed).

Eyal Schneider
And in fact, arrays have a type safety flaw because that's allowed, but the flaw is only detected at runtime, not compile time. I could follow your code with `nums[0] = new Double(8.9)` and that would compile. Only at runtime would it throw an exception.
Daniel Martin
You cannot store any instance of the superclass in the subclass array. Therefore an array of a subclass IS NOT an array of a superclass according to the [Liskov Substitution Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle). But this is only detected at runtime, as @Daniel noted.
Christian Semrau
Of course. The limitations in the generic code is intended to protect against the unexpected ClassCastException, while arrays do not protect against ArrayStoreException. But from the compiler's point of view, Integer[] IS a Number[], and the casting is allowed, assuming that the programmer is aware of the actual array type.
Eyal Schneider
List<Integer> intList = new ArrayList<Integer>(); List<? extends Number> numList = intList; //Does work though
Robert
Ah, but that's okay because after that `numList.add(new Double(8.9))` won't compile.
Daniel Martin
@Daniel: See the comments above. It will compile, but throw ArrayStoreException at runtime. Arrays impose less compile time restrictions (hence the apparent "benefit"), but the price is loss of runtime type safety.
Eyal Schneider
@Eyal: I was responding with my "won't compile" comment to Robert's comment with `List<? extends Number>`.
Daniel Martin
+4  A: 

Arrays are more efficient, both in terms of processing time and memory footprint. This particularly applies if you are operating on primitive types, such as int or long, since List requires all elements to be wrapped in an Object (such as Integer or Long). While the autoboxing features introduced by Java 5 reduces the amount of code you need for such wrapping and unwrapping, it does not remove the performance issues, as wrapper objects are still being created.

However, most applications probably do not have any performance bottlenecks related to these issues, so in most cases, List and other collections should do fine. In these cases, the ease of programming outweighs the increase in memory or CPU usage, and List is the right choice.

markusk
+1: Arrays are more efficient, but you usually don't need that. In all the business applications I have written, there never was a performance issue that could be solved by replacing collections with arrays. Only in number crunching tools have I seen the need to avoid wrapping primitives and therefore the need to stick with arrays.
Christian Semrau
@Christian: Agreed, in most situations collections do just fine.
markusk
One big flaw of java generics is the missing support for primitives. At least some third party librarys implement collection classes for primitive types, which removes at least the overhead of boxing and unboxing.
josefx
+3  A: 

If there are any important benefits of using arrays that I miss?

Constant-time access to any element with a very small constant. To access an array element safely takes just a few instructions: a couple of loads, a compare, and a branch. The branch is typically successful nearly 100% of the time, so modern hardware does an excellent job predicting it.

Norman Ramsey
A: 

It really depends on the situation. Arrays are incredibly fast, but they are a fixed size and they may not be suitable if the amount of data that you need to process is very large. Collections, on the other hand, have varying degrees of performance, depending on the particular subclass. The ArrayList, for example, is mostly just a wrapper around an array and so should have similar iteration speed and memory requirements. For myself, I typically use the Iterable<T> interface wherever possible, since that gives the greatest flexibility to my code, allowing it to process in-memory resident arrays as well as lists of data that are fetched from a file or over a network using a custom iterable/iterator class. When it is time to actually instantiate the Iterable object that I pass-in, that depends on the specific situation; if I know the size and it will fit in memory at once, then I simply use an array, while if it will possibly grow, then I will use an ArrayList, and if it needs fast insertion at both ends, then I will use a LinkedList.

Michael Aaron Safyan