&. |

A software developer’s musings on software development

Array-casting in Java

Warning: I wrote this blog in 2007. That is a long time ago, especially on the internet. My opinions may have changed since then. Technological progress may have made this information completely obsolete. Proceed with caution.

Since I haven’t posted anything this week, I figured I’d share something annoying I discovered in Java: you can’t assume that you can put an object of type T into a T array (unless you happen to know that T is declared as a final class).

Take for example this code, which tries to put an Integer (which is an Object) into an array of Objects:

public static void main(String[] args)
{
  Object[] objects = new String[2];
  objects[0] = "ABC";
  objects[1] = new Integer(5);
}

This code compiles with no problem but when run it gives a runtime error on the objects[1]= line. But if the array were declared as new Object[2]; it would run with no complaints.

The problem is that you’re allowed to cast an array of type T to an array of a super-type of T, but you don’t really have an array of the super-type. I imagine they decided to allow this because of the usefulness of casting arrays to super-types for reading the data. But it opens up a whole new set of bugs that most of the time you wouldn’t even think to check for (especially if the array is declared in someone else’s code).

Apparently C# has controversially included the same feature.