问题和练习:泛型

原文: https://docs.oracle.com/javase/tutorial/java/generics/QandE/generics-questions.html

  1. 编写一个通用方法来计算集合中具有特定属性的元素数(例如,奇数整数,素数,回文数)。

  2. 下面的类会编译吗?如果没有,为什么?

    1. public final class Algorithm {
    2. public static <T> T max(T x, T y) {
    3. return x > y ? x : y;
    4. }
    5. }
  3. 编写一个通用方法来交换数组中两个不同元素的位置。

  4. 如果编译器在编译时擦除所有类型参数,为什么要使用泛型?

  5. 类型擦除后,以下类转换为什么?

    1. public class Pair<K, V> {
    2. public Pair(K key, V value) {
    3. this.key = key;
    4. this.value = value;
    5. }
    6. public K getKey(); { return key; }
    7. public V getValue(); { return value; }
    8. public void setKey(K key) { this.key = key; }
    9. public void setValue(V value) { this.value = value; }
    10. private K key;
    11. private V value;
    12. }
  6. 在类型擦除后转换为以下方法是什么?

    1. public static <T extends Comparable<T>>
    2. int findFirstGreaterThan(T[] at, T elem) {
    3. // ...
    4. }
  7. 以下方法会编译吗?如果没有,为什么?

    1. public static void print(List<? extends Number> list) {
    2. for (Number n : list)
    3. System.out.print(n + " ");
    4. System.out.println();
    5. }
  8. 编写一个通用方法来查找列表[开始,结束]范围内的最大元素。

  9. 下面的类会编译吗?如果没有,为什么?

    1. public class Singleton<T> {
    2. public static T getInstance() {
    3. if (instance == null)
    4. instance = new Singleton<T>();
    5. return instance;
    6. }
    7. private static T instance = null;
    8. }
  10. 给出以下类:

    1. class Shape { /* ... */ }
    2. class Circle extends Shape { /* ... */ }
    3. class Rectangle extends Shape { /* ... */ }
    4. class Node<T> { /* ... */ }

    下面的代码会编译吗?如果没有,为什么?

    1. Node<Circle> nc = new Node<>();
    2. Node<Shape> ns = nc;
  11. 考虑这个类:

    1. class Node<T> implements Comparable<T> {
    2. public int compareTo(T obj) { /* ... */ }
    3. // ...
    4. }

    下面的代码会编译吗?如果没有,为什么?

    1. Node<String> node = new Node<>();
    2. Comparable<String> comp = node;
  12. 如何调用以下方法来查找列表中的第一个整数,该整数是指定整数列表的相对素数?

    1. public static <T>
    2. int findFirst(List<T> list, int begin, int end, UnaryPredicate<T> p)

    注意,如果 gcd( a,b )= 1,则两个整数 ab 是相对素数,其中 gcd 是最大公约数的缩写。

Check your answers.