Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does java allow this?

it is syntactically legal to do this:

String [] s = new String[1];
Object [] o = s;

o[0] = new Integer(42);

but of course it will crash at runtime.

my question is: what is the point of allowing this assignment in the first place?

like image 395
clamp Avatar asked Mar 02 '26 03:03

clamp


2 Answers

The problem is the assignment Object [] o = s; - I assume that's what you mean by "this".

The technical term is array covariance, and without it, you could not have code that deals with arrays generically. For example, most of the non-primitive-array methods in java.util.Arrays would be useless as you could only use them with actual Object[] instances. Obviously, this was considered more important by the designers of Java than complete type safety.

There is an alternative solution, which you see when looking at Java's generics introduced in Java 5: explicit covariance via wildcards. However, that results in considerable added complexity (see the constant stream of questions about the ? wildcard), and Java's original designers wanted to avoid complexity.

like image 172
Michael Borgwardt Avatar answered Mar 04 '26 17:03

Michael Borgwardt


The point of allowing that kind of assignment is that disallowing it would make things like the following impossible:

ArrayList[] lists = new ArrayList[10];
lists[0] = new ArrayList();

List[] genericLists = lists;
lists[0].add("someObject");

If the compiler forbids your String -> Object case, then it would also have to forbid ArrayList -> List and any other instance of assigning from a subclass to one of its superclass types. That kind of makes a lot of the features of an object-oriented language such as Java useless. Of course, it's much more typical to do things like:

List[] lists = new List[10];
lists[0] = new ArrayList();
lists[0].add("someObject");

But regardless, the compiler can't filter out these cases without simultaneously disallowing many useful and legitimate use-cases, so it's up to the programmer to make sure that what they are doing is sane. If what you want is an Object[], then declare your variable as such. If you declare something as String[], cast it to an Object[], and then forget that what you really have is a String[], then that is simply programmer error.

like image 45
aroth Avatar answered Mar 04 '26 15:03

aroth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!