Sub topic 12
Covariance, Runtime Checks, and Generic Array Restrictions
This chapter assumes you can create arrays and use object references. You will learn why some array assignments are allowed but can still fail when the program runs.
Array covariance
A subtype is a more specific type. For example, String is a subtype of Object, so a String value can be used where an Object is expected.
Java also lets you assign a String[] reference to an Object[] variable. This rule is called array covariance.
The assignment does not create a new array. Both variables refer to the same array, which is still a String[].
A runtime check
A runtime check is a check Java performs while a program is running. When you store a value in an array, Java checks whether the value fits the array’s actual element type.
Save this example as ArrayCheck.java and run it with javac ArrayCheck.java followed by java ArrayCheck:
public class ArrayCheck {
public static void main(String[] args) {
String[] names = {"Ada"};
Object[] items = names;
items[0] = "Lin";
try {
items[0] = new Object();
} catch (ArrayStoreException error) {
System.out.println("The object was rejected.");
}
System.out.println(names[0]);
}
}The program prints The object was rejected. and then Lin.
The Java compiler, which checks the program before it runs, sees items as an Object[]. It therefore allows the attempt to store an Object. But the actual array is a String[], so Java rejects the value at runtime.
An ArrayStoreException is an error raised when a value does not fit an array’s actual element type. The try and catch blocks handle that error, so the program continues. The failed assignment leaves Lin in the array.
A string fits in the actual array, and null is also allowed. By contrast, an array created as new Object[1] can hold an ordinary Object.
Why generic arrays are restricted
A generic type is a type that takes another type as a setting. For example, List<String> is a list set to hold strings. The String in it is called a type argument.
You cannot create an array with new List<String>[2]. You can declare a variable of type List<String>[], but that does not create an array.
The reason is a difference between arrays and generics:
- An array keeps its actual element type available for runtime checks.
- Java normally removes generic type arguments at runtime. This is called type erasure. A runtime check can recognize a
List, but it cannot check that it is specifically aList<String>.
If Java allowed new List<String>[2], array covariance could let code try to put a List of another element type into it. The array’s runtime check could not detect the wrong type argument.
The restriction also applies to a generic type parameter: if T stands for a type, you cannot create an array with new T[2].
Use a list of lists instead
For groups of strings, a List<List<String>> avoids creating a generic array. Save this example as Groups.java:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Groups {
public static void main(String[] args) {
List<List<String>> groups = new ArrayList<>();
groups.add(Arrays.asList("Ada", "Lin"));
System.out.println(groups.get(0).get(1));
}
}Run it with javac Groups.java and java Groups. It prints Lin. The compiler checks that each added group is a List<String>.
There is one useful exception to the array restriction: new List<?>[2] is allowed. The ? is a wildcard, meaning the list’s element type is unknown. Such an array can hold lists with different element types, but you cannot safely treat every list as a List<String>.
Exercise
If Object[] values = new String[1];, what happens when you assign new Object() to values[0]?
Show answer
Java raises an ArrayStoreException. The actual array is a String[], so it cannot hold an ordinary Object.
Exercise
Why is new List<String>[2] forbidden?
Show answer
At runtime, Java cannot check a list’s String type argument. That would make the array’s store check unable to prevent some wrong-type values.