Home >Java >javaTutorial >Why Can\'t We Bound Generic Type Parameters with \'super\' in Java?
When working with generics in Java, it is often necessary to bound type parameters to ensure compatibility with specific types. The 'super' keyword can be used to specify that a type parameter must be a superclass or superinterface of a specified type. However, this usage is only allowed with wildcards, not with type parameters.
In the Collection interface, the toArray method is declared as:
<T> T[] toArray(T[] a);
This method allows you to convert a collection of elements of type 'T' into an array of elements of the same type. However, you cannot write the method as follows:
<T> <S super T> S[] toArray(S[] a);
The reason for this is that the 'super' keyword in generics is used to bound wildcards, not type parameters. In the above example, you are trying to use 'super' to bound the type parameter 'S' to be a superclass or superinterface of 'T'. This usage is not allowed because it could potentially lead to type safety issues.
For example, consider the following code:
List<Integer> integerList = new ArrayList<>(); Integer[] integerArray = new Integer[5]; Number[] numberArray = new Number[5]; Object[] objectArray = new Object[5]; // hypothetical method integerList.toArray(super T numberArray)
According to your proposed syntax, the above code would allow the following type assignments:
integerList.toArray(super T integerArray) // compiles fine! integerList.toArray(super T numberArray) // compiles fine! integerList.toArray(super T objectArray) // compiles fine!
However, since 'String' is not a superclass of 'Integer', the following code should not compile:
integerList.toArray(super T stringArray) // should not compile
But again, since 'Object' is a superclass of both 'Integer' and 'String', the following code would still compile, even though it would throw an 'ArrayStoreException' at runtime:
integerList.toArray(super T stringArray) // compiles fine!
This behavior is undesirable because it could lead to type safety violations. To prevent this, Java does not allow you to use 'super' to bound type parameters. Instead, you can only use 'super' to bound wildcards.
For example, you could Rewrite the toArray method as follows using a wildcard:
<T> T[] toArray(T[] a);
This method allows you to write code that is both type-safe and flexible. For example, the following code compiles and does not throw an 'ArrayStoreException' at runtime:
List<Integer> integerList = new ArrayList<>(); Integer[] integerArray = new Integer[5]; Number[] numberArray = new Number[5]; Object[] objectArray = new Object[5]; integerList.toArray(objectArray);
The above is the detailed content of Why Can\'t We Bound Generic Type Parameters with \'super\' in Java?. For more information, please follow other related articles on the PHP Chinese website!