大学MOOC Java核心技术(高阶)(华东师范大学)1206500807 最新慕课完整章节测试答案
第二章Java泛型
第二章Java泛型测验
1、单选题:
给定代码import java.util.*;
class Wash<T ____________ Collection>
{
T item;
public void clean(T items) {
System.out.println("Cleaned " + items.size() + " items");
}
}
public class LaundryTime {
public static void main(String[] args) {
Wash<List> wash = new ____________
wash.clean(Arrays.asList("sock", "tie"));
}
}下列选项哪个可以添加到程序中,并输出Cleaned 2 items。
选项:
A: extends, Wash<ArrayList>();
B: extends, Wash<List>();
C: super, Wash<ArrayList>();
D: super, Wash<List>();
答案: 【 extends, Wash<List>();】
2、单选题:
给定以下代码import java.util.*;
public class ExtendingGenerics {
private static <_____________ , U> U add(T list, U element) {
list.add(element);
return element;
}
public static void main(String[] args) {
List<String> values = new ArrayList<>();
add(values, "duck");
add(values, "duck");
add(values, "goose");
System.out.println(values);
}
}以下哪个代码添加进去,可以使得程序正常编译。
选项:
A: ? extends Collection<U>
B: ? implements Collection<U>
C: T extends Collection<U>
D: T implements Collection<U>
答案: 【 T extends Collection<U>】
3、单选题:
给定以下代码import java.io.*;
class LastError<T> {
private T lastError;
public void setError(T t){
lastError = t;
System.out.println("LastError: setError");
}
}
class StrLastError<S extends CharSequence> extends LastError<String>{
public StrLastError(S s) {}
public void setError(S s){
System.out.println("StrLastError: setError");
}
}
class Test {
public static void main(String[] args) {
StrLastError<String> err = new StrLastError<String>("Error");
err.setError("Last error");
}
}其输出结果是
选项:
A: It prints the following: StrLastError: setError.
B: It prints the following: LastError: setError.
C: It results in a compilation error.
D: It results in a runtime exception.
答案: 【 It results in a compilation error.】
4、判断题:
以下代码能够编译通过.public final class Algorithm {
public static <T> T max(T x, T y) {
return x > y ? x : y;
}
}
选项:
A: 正确
B: 错误
答案: 【 错误】
5、判断题:
以下代码能够编译通过.public static void print(List<? extends Number> list)
{
for (Number n : list)
System.out.print(n + " ");
System.out.println();
}
选项:
A: 正确
B: 错误
答案: 【 正确】
6、判断题:
以下代码可以编译通过。public class Singleton<T>
{
public static T getInstance()
{
if (instance == null)
instance = new Singleton<T>();
return instance;
}
private static T instance = null;
}
选项:
A: 正确
B: 错误
答案: 【 错误】
7、判断题:
给定以下代码,class Shape { /* ... */ }
class Circle extends Shape { /* ... */ }
class Rectangle extends Shape { /* ... */ }
class Node<T> { /* ... */ }那以下代码可以编译通过。Node<Circle> nc = new Node<>();
Node<Shape> ns = nc;
选项:
A: 正确
B: 错误
答案: 【 错误】
8、判断题:
给定以下代码,class Node<T> implements Comparable<T>
{
public int compareTo(T obj) { /* ... */ }
// ...
}那以下代码可以编译通过。Node<String> node = new Node<>();
Comparable<String> comp = node;
选项:
A: 正确
B: 错误
答案: 【 正确】
9、判断题:
以下Pair泛型类public class Pair<K, V> {
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey(); { return key; }
public V getValue(); { return value; }
public void setKey(K k
