Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Why is this generic array creation?

843793Feb 12 2007 — edited Feb 12 2007
HashSet<Long>[] hashsets = new HashSet<Long>[10];

This isn't creating an array of a generic types, it is creating an array of a parameterized type. After erasure, the underlying type is exactly what we need it to be. I don't understand why the compiler cannot create an array of HashSets and then treat it as a HashSet<Long>[]. How is this any different than:

HashSet<Long> hashset = new HashSet<Long>();

The concept is the same. Create a HashSet object, and then treat it as a HashSet<Long>. There shouldn't be a problem with the first line simply because it's an array. The problem isn't that the compiler doesn't know the type of the array at runtime because it does! It is an array of HashSets! And I don't see how the first example is any less type safe than the second example. You can cast the HashSet<Long> to a HashSet<String> just as easily as you can insert a HashSet<String> into a HashSet<Long>[]. Both of these cases have just as much potential for problems as the other.

I understand why you cannot have "class MyClass<T>", and within the class perform the following:

T[] tarray = new T[10];

In this case, yes, the compiler doesn't know what the type will be at runtime, but this is totally different than calling "new HashSet<T>[]".

Please don't tell me to just use ArrayList<HashSet<Long>>. I just want to know the logic behind the decision not to allow this. Also, I know the following will work:

HashSet<Long>[] hashsets = (HashSet<Long>[])new HashSet[10];
HashSet<Long>[] hashsets = (HashSet<Long>[])new HashSet<?>[10];

But why should we have to go through all that trouble! It seems so incredibly unecessary to me.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 12 2007
Added on Feb 12 2007
1 comment
235 views