Search code examples
javaarraysgenericsrestriction

Is there a way to restrict generic parameters to be arrays?


I tried "T extends Array" but that doesnt work,

public class Foo<T extends Array> {
    { ...}
}

public class Bar {
    {
        Foo<int[]> f; <-- Error
    }
}

From what I saw, I dont think its posible, but hey, I'm not a Java guru


Solution

  • No, you can't extend a class with Array. You can only extend Java types like classes, interfaces etc. (You can also not extend int since it is a primitive type). If you want a new type of array you have to create an array of that object e.g. int[] intArray = new int[5]; or Foo[] foo = new Foo[5];

    read here for why it is not allowed