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")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With