Content deleted Content added
Add code formatting. |
→Example: Lists: Remove final keyword for function parameters |
||
(One intermediate revision by the same user not shown) | |||
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:
This incompatibility
== Wildcard as parameter type ==
Line 71:
A <code>List<? '''extends''' MyClass></code> is a list of objects of some subclass of <code>MyClass</code>, i.e. any object in the list is guaranteed to be of type <code>MyClass</code>, so one can iterate over it using a variable of type <code>MyClass</code><ref>[[Inheritance (object-oriented programming)]]</ref>
<syntaxhighlight lang="java">
public void doSomething(
for (final MyClass object : list) { // OK
// do something
Line 79:
However, it is not guaranteed that one can add any object of type <code>MyClass</code> to that list:
<syntaxhighlight lang="java">
public void doSomething(
final MyClass m = new MyClass();
list.add(m); // Compile error
Line 88:
A <code>List<? '''super''' MyClass></code> is a list of objects of some superclass of <code>MyClass</code>, i.e. the list is guaranteed to be able to contain any object of type <code>MyClass</code>, so one can add any object of type <code>MyClass</code>:
<syntaxhighlight lang="java">
public void doSomething(
final MyClass m = new MyClass();
list.add(m); // OK
Line 95:
However, it is not guaranteed that one can iterate over that list using a variable of type <code>MyClass</code>:
<syntaxhighlight lang="java">
public void doSomething(
for (final MyClass object : list) { // Compile error
// do something
|