Java Reference
In-Depth Information
You create an object of type LinkedList<Double> from the parameterized type to store elements of type
Double in the linked list. When you pass a value of type double to the addItem() method, the compiler
inserts a boxing conversion to type Double because that's the argument type that the method requires.
When you extract Double objects from the linked list and pass them to the toFahrenheit() method,
the compiler automatically inserts an unboxing conversion to extract the original double values and
those are passed to the method. You could equally well use the reference returned by getFirst() or
getNext() in an arithmetic expression; you would get the same unboxing conversion provided automat-
ically.
You can see how the printf() method is helpful in making the output more readable by limiting the
display of temperature values to two decimal places after the decimal point.
The Runtime Type of Generic Type Instances
Suppose you create two different types from the LinkedList<T> generic type:
LinkedList<Double> numbers = new LinkedList<>(); // List to store numbers
LinkedList<String> proverbs = new LinkedList<>(); // List to store strings
Clearly the variables numbers and proverbs are instances of different class types. One type represents a
linked list that stores values of type Double , and the other represents a linked list that stores values of type
String . However, things are not quite as straightforward as that. Because you have only one generic type,
both classes share the same Class object at runtime, which is the Class object that corresponds to the gen-
eric type, so their class type names are identical. Indeed, all types that you generate from a given generic
type share the same class name at run time. You can demonstrate this with the following example.
TRY IT OUT: The Run Time Types of Generic Type Instances
In this example you create two different instances of the LinkedList<T> generic type and see what their
type names are.
public class TestClassTypes {
public static void main(String[] args) {
LinkedList<String> proverbs = new LinkedList<>();
LinkedList<Double> numbers = new LinkedList<>();
System.out.println("numbers class name " +
numbers.getClass().getName());
System.out.println("proverbs class name " +
proverbs.getClass().getName());
System.out.println("Compare Class objects: " +
numbers.getClass().equals(proverbs.getClass()));
}
Search WWH ::




Custom Search