Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...