Wildcard (Java): Difference between revisions

Content deleted Content added
Add code formatting.
Covariance for generic types: Fix in-line citation issues
Line 4:
== Covariance for generic types ==
 
Unlike arrays (which are [[Covariance and contravariance (computer science)#Covariant arrays in Java and C#|covariant]] in Java{{sfn|Bloch|2018|loc=Chapter §5 Item 26: Don't use raw types|pp=117-122}}), different instantiations of a generic type are not compatible with each other, not even explicitly.{{sfn|Bloch|2018|loc=Chapter §5 Item 26: WithDon't use raw types|pp=117-122}} For example, the declarationdeclarations <code>Generic<Supertype> superGeneric; Generic<Subtype> subGeneric;</code> will cause the compiler wouldto report a conversion errorerrors for both castings <code>(Generic<Subtype>)superGeneric</code> and <code>(Generic<Supertype>)subGeneric</code>.{{sfn|Bloch|2018|loc=Chapter §5 Item 26: Don't use raw types|pp=117-122}}
 
This incompatibility maycan be softened by the wildcard if <code>?</code> is used as an actual type parameter.{{sfn|Bloch|2018|loc=Chapter §5 Item 26: Don't use raw types|pp=117-122}} <code>Generic<?></code> is a supertype of all parameterizarions of the generic type <code>Generic</code>.{{sfn|Bloch|2018|loc=Chapter §5 Item 31: Use bounded wildcards to increase API flexibility|pp=139-145}} This allows objects of type <code>Generic<Supertype></code> and <code>Generic<Subtype></code> to be safely assigned to a variable or method parameter of type <code>Generic<?></code>.{{sfn|Bloch|2018|loc=Chapter §5 Item 3126: Use bounded wildcards toDon't increaseuse APIraw flexibilitytypes|pp=139117-145122}} Using <code>Generic<? extends Supertype></code> allows the same, restricting compatibility to <code>Supertype</code> and its children.{{sfn|Bloch|2018|loc=Chapter §5 Item 31: Use bounded wildcards to increase API flexibility|pp=139-145}} Another possibility is <code>Generic<? super Subtype></code>, which also accepts both objects and restricts compatibility to <code>Subtype</code> and all its parents.{{sfn|Bloch|2018|loc=Chapter §5 Item 31: Use bounded wildcards to increase API flexibility|pp=139-145}}
 
== Wildcard as parameter type ==