Bear with me for a while. I know this sounds subjective and argumentative for a while, but I swear there is a question mark at the end, and that the question can actually be answered in an objective way...
Coming from a .NET and C# background, I have during recent years been spoiled with the syntactic sugar that generics combined with extension methods provide in many .NET solutions to common problems. One of the key features that make C# generics so extremely powerful is the fact that if there is enough information elsewhere, the compiler can infer the type arguments, so I almost never have to write them out. You don't have to write many lines of code before you realize how many keystrokes you save on that. For example, I can write
var someStrings = new List<string>();
// fill the list with a couple of strings...
var asArray = someStrings.ToArray();
and C# will just know that I mean the first var
to be List<string>
, the second one to be string[]
and that .ToArray()
really is .ToArray<string>()
.
Then I come to Java.
I have understood enough about Java generics to know that they are fundamentally different, above else in the fact that the compiler doesn't actually compile to generic code - it strips the type arguments and makes it work anyway, in some (quite complicated) way (that I haven't really understood yet). But even though I know generics in Java is fundamentally different, I can't understand why constructs like these are necessary:
ArrayList<String> someStrings = new ArrayList<String>();
// fill the list with a couple of strings...
String[] asArray = someStrings.toArray(new String[0]); // <-- HERE!
Why on earth must I instantiate a new String[]
, with no elements in it, that won't be used for anything, for the Java compiler to know that it is String[]
and not any other type of array I want?
I realize that this is the way the overload looks, and that toArray()
currently returns an Object[]
instead. But why was this decision made when this part of Java was invented? Why is this design better than, say, skipping the .toArray()
that returns Object[]
overload entirely and just have a toArray()
that returns T[]
? Is this a limitation in the compiler, or in the imagination of the designers of this part of the framework, or something else?
As you can probably tell from my extremely keen interest in things of the utmost unimportance, I haven't slept in a while...