0

I understand that due to the way java implements generic typing its impossible to instantiate new generic arrays inside generic methods. on top of this all generic collection in java are of the type "Object" at runtime.

A big use of generic types is having functions that process arrays of various types that are implemented as one generic function rather than using Polymorphism,this reduces redundancy.

for example I would like to have code such as this:

    public static <V> V[] operateOnArray(V[] sourceArr) {
        V[] returnArr = new V[sourceArr.length];
        for (int i = 0; i < sourceArr.length ; i++) {
            returnArr[i] = utils.process(member);
        }
        return returnArr;
    }

However within this code V[] cannot be instantiated directly... Is this still possible to make a function that returns a new generic array, or is there a sufficiently elegant workaround?

  • `V[] returnArr = (V[])Array.newInstance(sourceArr.class.getComponentType(), sourceArr.length);` – Maurice Perry Jan 21 '19 at 11:59
  • @MauricePerry this has me confused for some time, if `Array::newInstance` does not make it type safe and still requires a `SupressWarnings`; why not use `(V[])newObject[...]` instead? – Eugene Jan 21 '19 at 12:01
  • @Eugene what is `newObject`? – Maurice Perry Jan 21 '19 at 12:33
  • @MauricePerry my bad I meant `new Object[]` – Eugene Jan 21 '19 at 12:36
  • @Eugene you can, but it would not be an array of the correct type. There would be no type checking when you assign an element. – Maurice Perry Jan 21 '19 at 12:46
  • Why is it you *need* to make a new array? Could it be a list? – christopher Jan 21 '19 at 12:56
  • @MauricePerry I am a bit confused by your comment. Well, first `sourceArr.class.getComponentType()` can't work, so you need to pass an additional parameter for that, something like `operateOnArray(V[] sourceArr, Class clazz)`. then `Array.newInstance` returns an `Object`, so there is still casting involved to whatever type is needed, thus what "type checking" did you mean here? – Eugene Jan 21 '19 at 13:59
  • @Eugene my mistake: it's not `sourceArr.class.getComponentType()` but `sourceArr.getClass().getComponentType()`. As for type checking, try both, you will see what I mean. – Maurice Perry Jan 22 '19 at 06:18

0 Answers0