What is the difference between '&' and ',' in Java generics?
JavaGenericsJava Problem Overview
While reading the Java official tutorial about generics, I found that you can restrict the type argument (in this case is T
) to extend a class and/or more interfaces with the 'and' operator (&
) like this:
<T extends MyClass & Serializable>
I replaced the &
with ,
(by mistake and still works, with a minor warning).
My question is, is there any difference between these two:
<T extends MyClass & Serializable>
<T extends MyClass , Serializable> // here is with comma
And the example method:
static <T extends MyClass & Serializable> ArrayList<T> fromArrayToCollection(T[] a) {
ArrayList<T> arr = new ArrayList<T>();
for (T o : a) {
arr.add(o); // Correct
}
return arr;
}
Java Solutions
Solution 1 - Java
<T extends MyClass & Serializable>
This asserts that the single type parameter T
must extend MyClass
and must be Serializable
.
<T extends MyClass , Serializable>
This declares two type parameters, one called T
(which must extend MyClass
) and one called Serializable
(which hides java.io.Serializable
— this is probably what the warning was about).