Java: List<X> or X[] ?
Since the creation of Java 1.5, one’s been able to parametrize classes using generics, with a syntax similar to C++ templates.
Before Java 1.5, I would always return simple list data structures as arrays. This was
- Type-safe (e.g. User[] as opposed to List; the former one knows what’s in the collection, in the latter one doesn’t)
- One could find out the length of the collection with array.length (in contrast to C arrays)
But since Java 1.5, one has a choice. One could use the Java collections framework, now supporting generics, or still use arrays.
Perhaps it’s because I don’t like change, but I would still advocate using arrays as opposed to Lists:
- The generic information is thrown away at compile-time, so a List<X> and List<Y> look the same at run-time, whereas X[] and Y[] do not. Introspection, and getting exceptions at the time of a wrong array cast, and not later, are the benefits here.
- You can easily create an array declaratively. int[] x = new int[] { 1, 2 }; You can’t do the same with the collections frameworks.
- I’m sure arrays are faster
- Arrays are also simpler. I think one should, given two solutions to the same problem, nearly always take the simpler unless there’s a clear benefit of the more complex solution (which I don’t see in this case)
Maybe the point about faster and simpler aren’t really relevant points these days. But collections are still the sort of things which one accesses in inner loops. Consider the ways in which X[] is faster than List<X>:
- To iterate over the collection, with List<X> you need to create an Iterator. This also happens if you use the “foreach” construct.
- To get a particular element, or to get the length, you have to call methods, like aList.get(3).
It has been said that using Iterators is preferable to using a for loop over array indexes, for software design reasons. This may be the case in some special situations, but I really don’t think it’s an advantage in common usage.
- One can iterate over an array or collection with the Java 1.5 “foreach” keyword: so in this case the source code looks the same.
- The code “for (i=0; i<array.length; i++)”, i.e. non-iterator code, is not really difficult to write or difficult to read.