Sub topic 12
Covariance, Runtime Checks, and Generic Array Restrictions
This chapter builds on creating arrays and sharing them through references. It explains why some array assignments are allowed, why a later write can still fail, and why Java limits arrays of generic types.
Array covariance
A type tells Java what kind of value a variable can hold. A class describes a kind of object. For example, String is a class, and each string is also an Object.
A reference is a value that points to an object. An array variable holds a reference to an array.
Because every String is an Object, Java allows this assignment:
Object[] view = words;
Here, words can be a String[]. The assignment does not create a new array. Both variables point to the same String[].
This rule is called array covariance. It means that if one reference type is a more specific kind of another, an array of the specific type can be used where an array of the general type is expected.
For example:
- A
Stringis anObject. - A
String[]can be assigned to anObject[]variable. - The actual array is still a
String[].
This rule applies to arrays of reference types. It does not make int[] an Object[], because int is a primitive type, not a reference type. An int[] itself can still be assigned to an Object variable: every array is an object.
Why a write needs a runtime check
The compiler checks code before it runs. At runtime, the program is running and has actual objects in memory.
Suppose an Object[] variable points to a String[]. The variable’s declared type says that it can be used to write objects. But the actual array can hold only strings. Java checks each write to a reference-type array against the actual array’s element type.
Save this program as StoreCheck.java:
public class StoreCheck {
public static void main(String[] args) {
String[] words = {"Ada", "Lin"};
Object[] view = words;
view[0] = "Grace";
System.out.println(words[0]);
try {
view[1] = new Object();
} catch (ArrayStoreException error) {
System.out.println("The array rejected the object.");
}
System.out.println(words[1]);
System.out.println(view.getClass().getComponentType().getName());
}
}Compile it with javac StoreCheck.java, then run it with java StoreCheck.
The program prints Grace, the rejection message, Lin, and java.lang.String, each on a separate line.
Here is what happens:
wordsrefers to aString[].viewrefers to the same array, through anObject[]variable.- The write of
"Grace"succeeds because it is a string. - The compiler accepts
view[1] = new Object()becauseviewis declared asObject[]. - At runtime, Java sees that the actual array accepts strings, not arbitrary objects. It rejects the write.
An exception is a signal that something went wrong while a program was running. Java throws an ArrayStoreException for the rejected write. The catch block handles it, so the program continues. The rejected write does not change the array, so the second element is still "Lin".
The last line asks the array for its component type, the type of its elements. It reports java.lang.String, even though the reference used is named view and has type Object[].
If you wrote words[1] = new Object() directly, the compiler would reject it. The declared type String[] already tells the compiler that the write is invalid.
The limit of the runtime check
Java keeps an array’s component type available at runtime. For example, it can tell that an array is a String[] and reject a non-string value.
A generic type is a type with a place for another type. For example, List<String> describes a list of strings. List is a Java interface for a sequence of values, and String is its type argument.
Java handles generic type arguments differently from array component types. Most generic type arguments are removed from runtime type information by a process called type erasure. At runtime, Java can generally tell that an object is a List, but not that it was declared as a List<String> rather than a List<Integer>.
That difference matters for arrays. If Java allowed a new List<String>[], an array store check could check that a value is a List. It could not reliably check that the list’s elements are strings.
For that reason, Java rejects new List<String>[2].
How an unsafe cast can cause trouble
Java also has an unchecked cast: a conversion the compiler cannot fully verify. It can be used to get around the restriction, but it does not make the result safe.
The following program deliberately performs an unsafe cast. Save it as UnsafeLists.java:
import java.util.Arrays;
import java.util.List;
public class UnsafeLists {
public static void main(String[] args) {
List<?>[] slots = new List<?>[1];
@SuppressWarnings("unchecked")
List<String>[] strings = (List<String>[]) slots;
Object[] objects = strings;
objects[0] = Arrays.asList(Integer.valueOf(42));
System.out.println("The list was stored.");
try {
String value = strings[0].get(0);
System.out.println(value);
} catch (ClassCastException error) {
System.out.println("The element was not a string.");
}
}
}Compile and run it with javac UnsafeLists.java and java UnsafeLists.
The program prints two messages: The list was stored. and The element was not a string.
The symbol ? is a wildcard. In List<?>, it means “a list whose element type is not specified here.” Java allows new List<?>[1]: the array can hold lists without claiming that all of them contain strings.
The cast then claims that this array is a List<String>[]. Java can check that it is an array of lists, but it cannot check the claimed String type argument. The line starting with @SuppressWarnings hides the compiler warning for this demonstration. It does not fix the unsafe cast.
Next, covariance lets objects refer to the same array as an Object[]. The program stores a list containing an Integer, an object that holds a whole number. The array accepts the list because its runtime component type is List.
The failure comes later. The declaration List<String>[] tells the compiler that get(0) should produce a string. The actual value is an Integer, so Java throws a ClassCastException. That exception signals a failed type conversion.
Generic array restrictions and safer choices
A type parameter is a name for a type supplied later. In a generic method, the name T is often used for that purpose.
Java allows a variable or parameter of type T[]. But it rejects new T[2], because the method does not have the specific component type needed to create and check that array at runtime.
These are useful rules to remember:
| Form | Allowed? | Reason |
|---|---|---|
| `new String[2]` | Yes | The component type is known as `String`. |
| `new List<String>[2]` | No | The runtime cannot check the `String` type argument for stored lists. |
| `new List<?>[2]` | Yes | It does not claim a specific element type for the lists. |
| `new T[2]` | No | A type parameter does not supply a specific runtime component type. |
| A parameter of type `T[]` | Yes | An existing array can be passed in. |
When you need a group of lists that must all contain strings, a list of lists is a safer choice. The compiler can then check the declared generic types without an unsafe array cast.
Save this example as SafeLists.java:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SafeLists {
public static void main(String[] args) {
List<List<String>> groups = new ArrayList<>();
groups.add(new ArrayList<String>());
groups.get(0).add("Ada");
System.out.println(groups.get(0));
List<?>[] mixed = new List<?>[2];
mixed[0] = Arrays.asList("Lin");
mixed[1] = Arrays.asList(Integer.valueOf(42));
System.out.println(mixed[1].get(0));
String[] names = {"Mia", "Sam"};
System.out.println(first(names));
}
static <T> T first(T[] values) {
return values[0];
}
}Compile and run it with javac SafeLists.java and java SafeLists. It prints [Ada], 42, and Mia, each on a separate line.
groups holds lists of strings. An attempt to add a List<Integer> to groups would fail at compile time.
mixed is different: each slot may hold a list with a different element type. Reading an element from a List<?> gives an Object reference, because the list’s element type is not known there.
Finally, first accepts an existing T[]; it does not create one. The caller passes a nonempty String[], so T is String for that call. This method requires a nonempty array because it reads index zero.
Practice
Exercise
A method receives an Object[]. The caller passes a String[]. What happens if the method stores new Object() in an element?
Show answer
The code can compile, but the write throws ArrayStoreException at runtime. The actual array is still a String[], so it rejects a non-string object.
Exercise
Why is new List<String>[2] rejected, while new List<?>[2] is allowed?
Show answer
The runtime cannot check that a stored list has the String type argument. List<?> makes no claim about a specific element type, so an array of those list references is allowed.
Exercise
A generic method receives a T[]. Can it create another array with new T[3]? Does receiving the array change its actual component type?
Show answer
No to both. new T[3] is not allowed because the specific component type is not available from T at runtime. The passed array keeps the component type with which it was created.