3

I have the following code, but it won't compile:

Class<? extends something>[] classes = new Class<? extends something>[5]();

Why exactly won't this work? And is there a way around this? I also tried it with Class<?> and that didn't work either.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Tim
  • 4,015
  • 8
  • 32
  • 47
  • 1
    I'm not sure if those parentheses `()` are intentional, but they do not belong there (syntax error). By the way, if you remove them, then `Class>` will work. – BalusC Feb 23 '12 at 15:51
  • 1
    possible duplicate of [Initialize Java Generic Array of Type Generic](http://stackoverflow.com/questions/1025837/initialize-java-generic-array-of-type-generic) – Louis Wasserman Feb 23 '12 at 15:53
  • I clearly explained **why** the following statement doesn't compile. Many answers on SO doesn't explain why it doesn't compile, except by saying that it doesn't compile. – Buhake Sindi Feb 23 '12 at 16:15

2 Answers2

3

The answer has to do with Array Creation Expression.

The rule clearly states:

The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.

That's why your above code will never compile. In fact, the following compile-time error message shows (example):

/**
 * 
 */


/**
 * @author The Elite Gentleman
 *
 */
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Class<? extends Exception>[] classes = new Class<? extends Exception>[5];
    }

}

Test.java:17: generic array creation

Solution (that works, if you follow the above rule):

Class<? >[] classes = new Class<?>[5];

The above line compiles.

I hope this helps.

Buhake Sindi
  • 82,658
  • 26
  • 157
  • 220
-1

i think you should try removing () from the last

Class<? extends something>[] classes = new Class<? extends something>[5];
dku.rajkumar
  • 17,470
  • 7
  • 39
  • 57
  • Have you tried compiling it? Try for instance `Class extends Number>[] classes = new Class extends Number>[5];`. – BalusC Feb 23 '12 at 15:54
  • @dku.rajkumar: D'oh! I knew that. It still gives me the same error though "Cannot create a generic array of Class extends something>". – Tim Feb 23 '12 at 15:55