Raw Type References
The type of the reference s0 is the raw type Node. This case illustrates the non-generic paradigm of using a collection: We can put any object, but we can only get an Object. From Table 11.2, we see that we can put any object as data in a node of the raw type Node, but the compiler issues unchecked call warnings, as we are putting an object into a raw type node whose element type is not known. We can only get an Object, as we cannot be more specific about the data type.
Unbounded Wildcard References: <?>
The type of the reference s0 is Node<?>. The compiler determines that the actual type parameter for each method call is the wildcard ?—that is, any type. Obviously, we cannot set any data in a node whose element type cannot be determined. It might not be type-safe. And we cannot guarantee the type of its data either because the data type can be of any type, but we can safely read it as an Object. Note that we can always write a null, as the null value can be assigned to any reference.
Typical use of unbounded wildcard reference is in writing methods that treat the objects in a container as of type Object and make use of Object methods for their operation. The method below can print the data in any sequence of nodes, given the start node. The specific type of the data in the node is immaterial. Note also that the method is not dependent on any type parameter.
void printNodeDataSequence(Node<?> s0) { // Unbounded parameterized type
Node<?> next = s0.getNext(); // Returns node as Node<Object>
while (next != null) {
Object obj = next.getData(); // Object reference.
System.out.println(obj.toString()); // Call Object method
next = next.getNext();
}
}
Leave a Reply