Member-only story

Effective Java! Prefer Lists to Array

Kyle Carter
3 min readJan 19, 2021

When we want to hold an ordered, indexable collection of items in Java we have two main options: arrays and Lists (OK so there are other data structures but for the sake of this argument we will focus on Lists as it can serve the place of any generic collection as far as the rules that will be considered in the post are concerned).

These two data structures are different in many ways but one of the main things is arrays are covariant which simply means that if Sub is a subtype of Super that means that Sub[] is a subtype of Super[]. Lists on the other hand are invariant which means that List<Sub> would not be a subtype of List<Super>. This can seem like arrays have more capabilities than Lists but there are benefits to this. Let's look at one, consider the following:

Object[] objectArray = new Long[1];
objectArray[0] = "Store a non long"; //ArrayStoreException
List<Object> objectList = new ArrayList<Long>(); // Won't compile

So as we see here one of the nice things is that we can get some of our issues raised sooner at compile time rather than at runtime.

Another big difference between arrays and Lists is that arrays are reified which basically means that the array knows its type and enforces it at runtime. This is why, in the above example, it throws the ArrayStoreException at runtime, it knows its type and is enforcing it. In contrast, as discussed in a previous chapter, generics are implemented via type erasure and thus the type information…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet