简体   繁体   中英

What is the difference between '&' and ',' in 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;
}
<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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM