I'm really new to generics in Java. I'm trying to create a simple method to compare two arrays that would be of the same type, but I want to use a generic method. I've attached a MWE below:
public class MWE {
public static void main(String[] args){
int[] test1,test2;
test1 = new int[2];
test2 = new int[2];
checkArray(test1,test2);
}
private <T> boolean checkArray(T[] check, T[] test) {
if(check.length != test.length)
return false;
for(int i=0;i<check.length;i++)
if(check[i]!=test[i])
return false;
return true;
}
}
When I try to compile, I get:
MWE.java:6: <T>checkArray(T[],T[]) in MWE cannot be applied to (int[],int[])
checkArray(test1,test2);
^
1 error
Generics works only for Objects, you have to have overloaded methods for primitive arrays. (In which you can switch to Integer[], Boolean[] and so on)
Try using Integer[] instead of int[].
In more detail:
Java Generics always work with classes, so when working with a generic like this, you need to use the class version of each type. Since Java automatically converts an int value to an Integer object value via autoboxing, there really shouldn't be any difference in your code other than the name of the type used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With