On the first part of this article I explained why java generics don’t allow up-casting for generified types. In this part we will see why, arrays don’t have that restriction, and the implications for reflection.
If generified lists aren’t allowed to up-cast, why arrays are?
The reason is very simple: arrays don’t erase their element type. At runtime, each array knows exactly which kind of element it should allow in. If you try this code:
String[] stringArray = new String[1];
Object[] objectArray = stringArray; // Perfectly normal
The compiler allows you to up-cast. What if we try to put something in the string array, that is not a string?
2 Dec 2014
When you use a compile-time typed language, like Java, you expect that types in each variable will help you by restricting the possibilities for a value. Instead of being able to do everything, you want to do things that are valid in your domain.
Discussions aside about strong vs weak typing, when you code with types you think of types as sets. A variable can be one of the elements of the implicit set for its type. Thus Integer a
means that variable ‘a’ will be one of the elements in the Integer set, and only that.
If you have a String variable ‘a’ and want to assign its value to a variable ‘b’ of type Object:
String a = "A";
Object b = a;
2 Dec 2014