3

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

Juan
  • 124
  • 2
  • 8

2 Answers2

2

If you want to restrict the type variable T to array-of-references types, you can instead have T be the component type, and restrict the component type, and use T[] where you need the array type, i.e. instead of

public class Foo<T extends Object[]> {
   T obj;
}

Foo<String[]> f;

you would have

public class Foo<T extends Object> {
   T[] obj;
}

Foo<String> f;

If you want to allow T to be array-of-primitives types too, that's not possible without allowing non-array reference types too, because the only supertype of array-of-primitive types like int[], boolean[], etc. is Object (and perhaps also Cloneable and Serializable). There is no supertype of "just" primitive and reference arrays. The most restrictive you can do would be something like

public class Foo<T extends Cloneable & Serializable>

and if you did that, you would not be able to do anything with T except the things that you can do to any Object anyway (note that neither the Cloneable nor Serializable interfaces provide any methods), so then you might as well not restrict T at all.

newacct
  • 119,665
  • 29
  • 163
  • 224
0

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

TheQuestioner
  • 724
  • 2
  • 8
  • 13
  • I didnt meant to extend array, i just wanted to know if there was a wild card for restricting parameters, mainly to use shared things like .length and such. I can use a wayaround for objects but not primitive types, but luckily I just had to repeat code 8 times, thanks! – Juan Mar 18 '18 at 03:04