Java Reference
In-Depth Information
numbers class name LinkedList
proverbs class name LinkedList
Compare Class objects: true
obj class name LinkedList
obj in proverbs class name LinkedList
Where the compiler recognizes unsafe casts, you get a warning message to indicate that you have a po-
tential problem. You should use such casts only when they are absolutely necessary, and you should al-
ways double-check that the cast is valid. Of course, situations arise where such casts are unavoidable.
One example is when you are deserializing objects that are instances of a class produced from a generic
type. You try this later in this chapter.
NOTE One further point to keep in mind about types that you create from a generic
type: Because all types that you produce from a generic type have the same runtime
type, you cannot use the instanceof operator to test for such types.
Relationships between Generic Type Instances
It's easy to be misled about whether types that you create from a generic type are related. Suppose you create
an object as follows:
LinkedList<String> strings = new LinkedList<>(); // A list of strings
You have created a linked list that store objects of type String . Suppose you now create another linked
list:
LinkedList<Object> things = new LinkedList<>(); // A list of objects
This stores objects of type Object organized as a linked list. Of course, it also stores objects of any type
that is a subclass of Object , so any class type is acceptable. Is there any relationship between the type of
things , which is LinkedList<Object> , and the type of strings , which is LinkedList<String> ? Super-
ficially, you might jump to the conclusion that there is; after all, Object is a superclass of every class type,
including type String . However, if you think about it, the relationship between the type arguments is an
irrelevancy, and the conclusion would be wrong. The types just happen to be produced by a single generic
type, LinkedList<> , but there's no reason why the type argument that you use should establish any rela-
tionship between these types, no more than there would be between two ordinary collection classes that you
might define to store String objects and Object objects.
Multiple Type Parameters
The LinkedList<T> type has a single type parameter, but in general you can define a generic type with
as many type parameters as you wish. Suppose that you want to define a generic type that defines a set of
Search WWH ::




Custom Search