Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method - "private <T> boolean (T[], T[])"

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
like image 947
zje Avatar asked May 04 '12 20:05

zje


2 Answers

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)

like image 140
Hurda Avatar answered Oct 20 '22 18:10

Hurda


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.

like image 30
zostay Avatar answered Oct 20 '22 20:10

zostay