Generics and the Use of
In Java, generics allow for type-safe operations over a wider range of types. However, questions arise when choosing between
Map<String, Class<? extends Serializable>> expected = null; Map<String, Class<java.util.Date>> result = null; assertThat(result, is(expected));
This code fails to compile due to the incorrect argument type passed to the assertThat method, which expects a Matcher extends T> instead of Matcher
Covariance states that a subtype can be safely assigned to a supertype. In other words, a Class extends Serializable> object can be assigned to a Class extends T> object. However, the opposite is not true: a Class extends T> object cannot be assigned to a Class extends Serializable> object.
This is because covariance only applies to the type parameter itself, not to the type arguments it contains. In our example, java.util.Date is a subtype of Serializable, but Class extends Serializable> is not necessarily a subtype of Class extends Date>.
Changing the signature of the assertThat method to Matcher extends T> addresses this issue by allowing a matcher that matches any subtype of the actual type. This provides the necessary flexibility for situations like the one in the code snippet.
However, it's important to note that there are potential downsides to using
Regarding the genericity of the assertThat method, it allows for type checking to ensure that the matcher used is compatible with the result type. While this does not completely eliminate the possibility of runtime errors, it adds a level of safety by preventing incompatible matches.
The above is the detailed content of When Should I Use `` vs. `` in Java Generics?. For more information, please follow other related articles on the PHP Chinese website!