Java Reference
In-Depth Information
Directory "TryWildCard"
You should get essentially the same output as before except that the sorted data is listed with each item
on a separate line.
How It Works
You have a static method defined in the
TryWildcard
class that lists the elements in any
LinkedList<>
object. You use this to list the contents of objects of type
LinkedList<Integer>
and
LinkedList<String>
. The
listAll()
method relies only on the
toString()
method being imple-
mented for the objects retrieved from the linked list. This is the case for any type of object because
the
toString()
method is always inherited from the
Object
class. Of course, relying on the inherited
toString()
method to represent an object in output is not ideal in many cases.
Constraints on a Wildcard
It may be the case that you'd like to limit a wildcard specification to some extent — after all, allowing any
non-primitive type is an incredibly wide specification. You can explicitly constrain a wildcard specification.
One possibility is to specify that it extends another type. This type of constraint is described as an
upper
bound
of the wildcard type because it implies that any subclass of the type that the wildcard extends is ac-
ceptable, including the type itself, of course.
Defining an Upper Bound
Suppose that you want to implement a method that serializes the objects stored in a
LinkedList<>
object.
A prerequisite is that the objects in the list implement the
Serializable
interface, whatever type they are.
You could define a static method to do this using an upper bound on the wildcard type specification:
public static void saveAll(LinkedList<? extends java.io.Serializable> list) {
// Serialize the objects from the list...
}
The parameter to the
saveAll()
method is of type:
LinkedList<? extends java.io.Serializable>
This says that the argument to the
saveAll()
method can be a linked list of objects of any type as long
as they implement the
Serializable
interface. Knowing that the objects in the list implement the
Serial-
izable
interface means that you can serialize them without knowing exactly what type they are. You can
just pass an object reference to the
writeObject()
method for the stream, and everything is taken care of.
To make the upper bound for a wildcard type
Object
, you just write it as:
? extends Object
You might think that specifying a wildcard with an upper bound that is type
Object
is stating the obvious
and not a useful thing to do. However, it does have a very useful effect. It forces the specification to repres-