Unbounded Type References: <Type>
The type of the reference s0 is Node<Number>, where Type is Number. The actual type parameter for each method call is determined to be Number. Thus the type of the parameter in the setData() method and the return value of the getData() method is Number. Therefore, we can pass the reference value of a Number or a subclass object of Number to the setData() method, and can assign the reference value returned by the getData() method to a reference of the type Number or a supertype of Number. In this case, we can put a Number, and get a Number.
Table 11.3 gives a summary of using parameterized references for set and get operations on a container. Here are some general guidelines for choosing a wildcard parameterized type:
- If we only want to get an element of type E from a container, we can use the upper bounded wildcard ? extends E for the reference.
- If we only want to put an element of type E into a container, we can use the lower bounded wildcard ? super E for the reference.
- If we want to both get and set elements of type E in a container, we can use the unbounded type E for the reference.
The following acronym might help to remember which parameterized references should be used to invoke get and set methods of a container: GESS (Get-extends-Set-super), meaning for a get method use reference of type <? extends T> and for a set method use reference of type <? super T>.
Table 11.3 Summary of Get and Set Operations Using Parameterized References
Type of s0 | Node | Node<?> | Node<? extends Number> | Node<? super Number> | Node<Number> |
Operation | |||||
set/put/write | Any object | Cannot put anythig except nulls. | Cannot put anything except nulls. | Number or subtype | Number or subtype |
get/read | Object only | Object only | Number | Object only | Number |
Leave a Reply