0
public class Test {

    class Genric<C extends Clazz> {
        C[] s;

        public Genric() {
            this.s = new SubClazz[3];
        }
    }

    class Clazz {

    }

    class SubClazz extends Clazz {

    }
}

The code gives an error at this.s = new SubClazz[3]; saying Type mismatch: cannot convert from Test.Clazz[] to C[]. Why does this error occur? How to solve this problem?

Can't Tell
  • 10,924
  • 9
  • 54
  • 84
  • 1
    possible duplicate of [How to create a generic array in Java?](http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) – Bruno César Feb 18 '15 at 11:54

1 Answers1

3

Because if C is bound to SomeOtherSubClazz for example, you would be doing

SomeOtherSubClazz[] s = new SubClazz[3];

which is analogous to:

Integer[] s = new Double[3];  // Integer and Double are both Numbers

Which obviously isn't type safe.

How to solve this obviously depends on what you want to do. Perhaps you can follow the approach suggested here: How to create a generic array in Java?

Community
  • 1
  • 1
aioobe
  • 383,660
  • 99
  • 774
  • 796