You cannot do this because of erasing styles , it's that simple.
Consider the following:
public static void main(String[] args) { List<? extends Number> l1 = Arrays.asList(1L, 2, 3L); List<? extends Number> l2 = Arrays.asList(1); isEqual(l1, l2); } public static <U, V> boolean isEqual(List<U> a, List<V> b) {
Here U == V ? l1 contains instances of Long and Integer , but l2 contains one instance of Integer .
I assume from your comment:
The first condition must be that their type is the same
what you need is the only type of U In this case, use the following signature:
public static <U> boolean isEqual(List<U> a, List<U> b) { }
nor will the above code compile anymore.
What you can also do is add 2 parameters that take classes:
public static <U, V> boolean isEqual(List<U> a, List<V> b, Class<U> uClass, Class<V> vClass) { if (!uClass.equals(vClass)) {
In this case, you can print a message if the specified classes do not match.
source share