Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a method that accepts an array of type x and another variable with the same type as the array

Tags:

java

generics

I would like to write a generic method that accepts an array and something else. Each of which could be whatever type, but they must be the same. I tried this, but I could still input anything into the method.

public static <T> boolean arrayContains(T[] array, T object){
    return Arrays.asList(array).contains(object);
}

I can call this method with arrayContains(new String[]{"stuff"}, new Pig()) but I only want it to accept arrayContains(new String[]{"stuff"}, "more stuff")

like image 970
Christopher Smith Avatar asked Oct 20 '22 20:10

Christopher Smith


1 Answers

What you are trying to do is tricky because any array (except an array of primitives) is an Object[], so as you have noticed, the method will always accept any array and any object.

One way around this could be to pass an explicit Class object, like this

public static <T> boolean arrayContains(T[] array, T object, Class<T> clazz)

Then you could write

arrayContains(new String[]{"stuff"}, "more stuff", String.class)

but not

arrayContains(new String[]{"stuff"}, new Pig(), String.class)
like image 82
Paul Boddington Avatar answered Oct 22 '22 09:10

Paul Boddington