0

I'm attempting to call a method that returns the identity of a generic array, supplying arrays of ints and doubles as test data. My typed parameters should implement the Comparable interface, but the compiler seems to complain:

method identity in class com.me.Test cannot be applied to given types;
  required: T[]
  found:    int[]
  reason: inference variable T has incompatible bounds
    equality constraints: int
    lower bounds: java.lang.Comparable<T>

I'm new to Java, so I'm probably missing something. Any thoughts?

Code:

public class Main {

    public static void main(String[] args) {
        int[] arr1 = {1};
        double[] arr2 = {1.0};
        System.out.println(Test.identity(arr1));
        System.out.println(Test.identity(arr2));
    }
}

public class Test {
    public static <T extends Comparable<T>> T[] identity(T[] x) {
        return x;
    }
}
2
  • 3
    Generics don't work with primitive element types. You would have to use Integer[] and Double[], respectively. Commented Feb 24, 2020 at 19:20
  • Does this answer your question? How to use an integer array for a generic method? Commented Feb 24, 2020 at 19:40

1 Answer 1

0

You could do something like the following (but without primitive element types, as generics do not work with them):

public class Main {

    public static <T> Class<?> identity(T[] array) {
    return array.getClass().getComponentType();
}

    public static void main(String[] args) {
        Integer[] arr1 = new Integer[]{1};
        Double[] arr2 = new Double[] {1.0};
        System.out.println(identity(arr1));
        System.out.println(identity(arr2));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.