110

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;
}
arshajii
  • 127,459
  • 24
  • 238
  • 287
Alin Ciocan
  • 3,082
  • 4
  • 34
  • 47
  • 5
    @Doorknob you are assuming the OP is using a keyboard and the same keyboard as you are using. – emory Aug 22 '13 at 16:04
  • 3
    @emory I think even that is wrong the direction - the error wasn't in his fingers but in his brain. Similarly to as if you'd tried to use 'include' instead of 'import' in a Java source file. You mistyped 'include', because your brain told you to type the wrong thing, which is possible for various reasons. – Nick Pickering Aug 22 '13 at 18:44
  • 2
    @Nicholas Pickering, is right! For me, it was not a mistype because of the keyboard, but because of the brain. When you write which interfaces a class implements, you separate them by comma. – Alin Ciocan Aug 23 '13 at 07:06

1 Answers1

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

arshajii
  • 127,459
  • 24
  • 238
  • 287