Chapter 21 Generics: Package Public Interface Public Int
Chapter 21 Generics: Package Public Interface Public Int
1. (a) will compile fine, but (b) has a compilation error on Line 3, because dates is
declared as a list of Date objects. You cannot assign a string to the list.
2. casting is needed in (a), but no casting is necessary in (b) with the generic type
ArrayList<Date>.
3. One important benefit is improving reliability and robustness. Potential errors can be
detected by the compiler.
4.
package java.lang;
5. No.
6. Yes.
7. To declare a generic type for a class, place the generic type after the class name, such
as GenericStack<E>. To declare a generic type for a method, place the generic type
for the method return type, such as <E> void max(E o1, E o2).
8. To declare a generic method, you place the generic type <E> immediately after the
keyword static in the method. A generic method can be invoked just like a regular
method. The compiler automatically discovers the actual type.
9. Bounded generic type such as <E extends AClass> specifies that a generic type must
be a subclass of AClass.
10. No, because list is of type int[], but the sort method requires E[], where E is an
object type.
11. No, because list is still of type int[], but the sort method requires E[], where E is
an object type.
12. When you use generic type without specifying an actual parameter, it is called a
raw type. A raw type is unsafe, because some errors cannot be detected by the
compiler. The raw type is allowed in Java for backward compatibility.
16. The program cannot be compiled, because the element type in stack1 is
GenericStack<String>, but the element type is stack2 is GenericStack<Object>.
add(stack1, stack2) cannot be matched.
18. Generic type information is used by the compiler to check whether the type is
used safely. Afterwards the type information is erased. The type information is not
available at runtime. This approach enables the generic code to
be backward-compatible with the legacy code that uses raw
types.
22. No. The JVM have to check the exception thrown from the try clause to see if it
matches the type specified in a catch clause. This is impossible, because the type
information is not present at runtime.
24. In the IntegerMatrix class, the add method is implemented by adding the two
numbers using the + operator. The multiply method is implemented by multiplying
the two numbers using the * operator. The zero method is implemented to return 0.
25. In the RationalMatrix class, the add method is implemented by adding the two
numbers using the add method in the Rational class. The multiply method is
implemented by multiplying the two numbers using the multiply method in the
Rational class. The zero method is implemented to return new Rational(0, 1).
26. You have to define it using: