I have the following code to check if a specific element is found in an array. I want this method to work with generic types.
public static <T> boolean InArray(T[] array, T needle) {
for (int i = 0; i < array.length; i ) {
if (needle == array[i]) {
return true;
}
}
return false;
}
But I can't figure out on how to call this function:
char[] arr = {'a', 'b', 'c'};
if (InArray(arr, 'c')) {
// In array
}
Yields the following error:
'InArray(T[], T)' in ... cannot be applied to '(char[], char)'
How do I make this generic method work?
CodePudding user response:
To call the method InArray, you need to wrap(box) your arguments to Character class. The below code explains how to call the method.
Character arr1[] = {'a', 'b', 'c'};
if (InArray(arr1, Character.valueOf('c'))) {
// In array
}
This is because you have array type as one of the parameters, the other primitive type parameter will not auto box to Character class. So you need to box the primitive type manually.
CodePudding user response:
Personally if I'm going to be comparing objects against my array. I use an arrayList. This allows you to use the 'contain' method
ArrayList<T> myArray = new ArrayList<>();
//Add your objects
if (myArray.contains(other_T_object)) {
//do stuff if condition is met
}
The reason why you are getting that error, is because your InArray method takes in an array of T objects as the first parameter and a single T object as your second parameter. You can't pass in an array of Char, because those are not specified in your methods declaration.
Your method will have to look like this.
public static boolean InCharArray(char[] array, char needle) {
for (int i = 0; i < array.length; i ) {
if (needle == array[i]) {
return true;
}
}
return false;
}