Reputation: 158
I want to make a function that takes an array and an object as its arguments:
public static int myFunction(Object[] array, Object obj) {
//Stuff
}
However, I want to ensure that the data type of obj
is the same as those stored in array
. I could throw an exception if they aren't the same by just using obj instanceof array[0]
, but I was curious if there's a way to specify this in the arguments of the function. I suspect there might be a way to do this with generics, but I'm not experienced enough with them to know for sure. Any help is much appreciated!
Upvotes: 0
Views: 47
Reputation: 863
If you want compile-time checking, you can use Generics:
public static <T> int myFunction(T[] array, T obj) {
//Stuff
}
You can read up a bit more on Generic Methods in the Java docs: https://docs.oracle.com/javase/tutorial/extra/generics/methods.html
Upvotes: 1
Reputation: 1
Just test if the class is equal
public class Program {
public static void main(String[] args) {
Object[] arr = new Object[3];
arr[0] = "akflj";
char test1 = 'a';
String test2 = "azdf";
System.out.println(test(arr, test1));
System.out.println(test(arr, test2));
}
public static boolean test(Object[] arr, Object item) {
if(item.getClass().equals(arr[0].getClass())) {
return true;
}
return false;
}
}
only functions correctly if an item is already in the array
Upvotes: 0