-1

Sorry if this is stupid question but i have the following method...

static <V> V[] getRange(V[] arr, V val, int range) {
    ArrayList<V> inRange = new ArrayList<>();
    int index = -1;
    for (int i = 0; i < arr.length; i++)
        if (arr[i] == val)
            index = i;
    for (int i = 0; i < arr.length; i++)
        if (Math.abs(i - index) <= range)
            inRange.add(arr[i]);
    return (V[]) inRange.toArray();
}

With this method you're supposed to be able to supply an element and a range, and return an array with nearby values. For example in psuedocode this what should happen.

getRange({1,2,3,4,5,6}, 5, 2) = {3,4,5,6}

However if i try to use this method with an int i get the following message:

The method getRange(V[], V, int) in the type myType is not applicable for the arguments (int[], int, int)

Ben Arnao
  • 88
  • 1
  • 9
  • https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#instantiate – Manos Nikolaidis May 11 '17 at 18:08
  • Primitive types will be implicitly converted to wrappers where applicable - however, the same cannot be said for arrays. You'll have to use an array of the Integer type. Integer[] range = getRange(new Integer[]{1,2,3,4,5,6}, 5, 2); Also, your generic method currently has a void return type instead of V[]. – Riaan Nel May 11 '17 at 18:12
  • Is there a generic method for converting primitive[] to wrapper[]? – Ben Arnao May 11 '17 at 19:10

1 Answers1

-1

Because a primitive cannot be used as a generic value. Try with the Integer class, it should be ok.

davidxxx
  • 125,838
  • 23
  • 214
  • 215