Nick
Nick

Reputation: 158

How can I pass an array as an argument to a function, as well as an object of the same data type of those stored in the array?

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

Answers (2)

beirtipol
beirtipol

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

CreepiMatze
CreepiMatze

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

Related Questions