开发者

Array type in generics

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.


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.


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.


You cannot create Array of generic type
Check generic Tutorial


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];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜