0

I am trying to figure out an answer to a problem in a textbook, but am having trouble. The question is asking me to have an input array checked to see if it contains an object that fits some feature. Every feature of this seems to be working fine except for when I attempt to implement the method using an input that is one of the classes implementing the interface.

Example:

main(){
  boolean r1 = has(input, checkFor2);
}

public static <T> boolean has(T[] input, Check<T> c){
  // does its check algorithm and returns a boolean
}

static public interface Check<T>{
  boolean isContained(T item);
}

static public class checkFor2 implements Check<Integer>{
  public boolean isContained(Integer val){
    // does a check algorithm
  }
}

// Other check algorithms implementing Check<T> follow as well.

The error I am getting is when "has" is called in the main method. It says:

The method has(T[], main.Check<T>) in the type main is not applicable for the arguments (int[], main.checkFor2)

Its suggestion is to change the class in the method to be a specific class instead of the interface which defeats the purpose of writing it this way.

Have I made some kind of rookie mistake in coding this?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
KM529
  • 372
  • 4
  • 17

1 Answers1

6

The problem is actually unrelated to your interface. It has to do with the fact you are giving a primitive int array int[] instead of an Integer[] array.

In the method

public static <T> boolean has(T[] input, Check<T> c){

the type T is inferred from what you give as parameter. In this case, you are giving int[] and Check<Integer>. However, an int[] cannot be boxed to an Integer[], so the type inference fails: T can't be inferred as an Integer.

The solution is therefore to change your primitive array into an Integer[] array, and send that as the first parameter to your method.

Community
  • 1
  • 1
Tunaki
  • 132,869
  • 46
  • 340
  • 423