java语言程序设计课后题----复习题/Chapter21泛型

本文深入探讨了Java中泛型的概念及应用,包括泛型的基本使用、类型通配符、限定泛型等,并解释了泛型如何提高代码的可靠性和健壮性。此外,还讨论了泛型在编译期的作用及其在运行时的表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值