Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between '&' and ',' in Java generics?

Tags:

java

generics

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;
}
like image 424
Alin Ciocan Avatar asked Aug 22 '13 13:08

Alin Ciocan


People also ask

What is the definition of the difference between?

The difference between two things is the way in which they are unlike each other.

What is difference between among and between?

The most common use for among is when something is in or with a group of a few, several, or many things. The most common use of between is when something is in the middle of two things or two groups of things. It is sometimes used in the phrase in between.

What is the difference between difference and differentiation?

To differ means to be different. To differentiate means to make (someone or something) different in some way.


1 Answers

<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).

like image 67
arshajii Avatar answered Oct 16 '22 18:10

arshajii