Chapter 21 Generics
1.(a)will compile fine , but (b) has a compilation error on Line3, because dates is declared as a list of Date objects.You cannot assign a string to the list.
1.(a) 没有编译错误,但是(b) 在第3行有编译错误,因为dates被定义为Date类的列表。不能把string赋值给list。
2.(a)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 erros can be detected by the compiler.
4.
package java.lang
public interface Comparable<T>{
public int compareTo(T o)
}
5.should be public ArrayList()
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 method, place the generic type for the method return type, such as
public static <E> void print(E[] list)
8.Bounded generic type such as <E extends AClass> specifies that a generic type must be a subclass of AClass.
9.When you use generic type without specifying an actual parameter, it is called a raw type. GenericStack is roughly equivalent to GenericStack<Object>, but they are not the same. GenericStack<Object> is a generic instantiation, but GenericStack is a raw type.
10.? is unbounded wildcard
? extends T is bounded wildcard
? super T is lower bounded wildcard
public static <T> void add(GenericStack<T> stack1,GenericStack<? super T> stack2){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
11.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.
12.The program can be compiled and run fine.
13.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.
14.No, Only ArrayList is loaded.
15.No, because the type information is not available at runtime.
16.Since all instances of a generic class have the same runtime class, the static variables and methods of a generic class is shared by all its instances. Therefore, it is illegal to refer a generic type parameter for a class in a static method or initializer.
17.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.