views:

104

answers:

4

I am trying to create an array of generic type. I am getting error:

 Pair<String, String>[] pairs;   // no error here

 pairs = new Pair<String, String>[10];   // compile error here

 void method (Pair<String, String>[] pairs)  // no error here.

I am confused. Any clues why this is happening.

+6  A: 

The reason behind this is that you can't create arrays of generic or parameterized types, only reifiable types (i.e. types which can be deduced at runtime).

It is possible though to declare such array types as variables or method parameters. This is a bit illogical, but that's how Java is now.

Java Generics and Collections deals with this and related issues extensively in chapter 6.

Péter Török
Good answer, could you explain why they did that?
javaguy
@javaguy, I can only speculate :-) following the guesses in JGaC. The possible reason was that the designers wanted to make the usage of arrays more convenient. It might have been better to avoid that, and prefer making the generic type system cleaner and safer. This would have made the usage of arrays more awkward in certain situations, thus actually speeding up the transition towards genuine collections for many developers - which would not be such a bad thing.
Péter Török
+4  A: 

Create the array without generic types:

Pair<String, String>[] pairs = new Pair[10];

The compiler won't complain and you won't have to use any @SuppressWarnings annotation.

seanizer
yup, no need of my complication. +1
Bozho
+1  A: 

You cannot create Array of generic type
Check generic Tutorial

org.life.java
+1  A: 

This construct compiles

import java.util.HashMap;


public class Test {
    class Pair<K,V> extends HashMap<K,V> {
    }

    public static void main(String[] args) {
        Pair<String, String>[] pairs = new Pair[10];
    }
}
stacker