问题与练习:泛型

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

  • 以下类会编译吗?如果没有,为什么?

public final class Algorithm {
    public static <T> T max(T x, T y) {
        return x > y ? x : y;
    }
}
  • 编写一种泛型方法来交换数组中两个不同元素的位置。

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

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

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 key)     { this.key = key; }
    public void setValue(V value) { this.value = value; }

    private K key;
    private V value;
}
  • 类型擦除后,以下方法转换为什么?
public static <T extends Comparable<T>>
    int findFirstGreaterThan(T[] at, T elem) {
    // ...
}
  • 可以编译以下方法吗?如果没有,为什么?
public static void print(List<? extends Number> list) {
    for (Number n : list)
        System.out.print(n + " ");
    System.out.println();
}
  • 编写泛型方法以在列表的\[begin, end\)范围内找到最大元素。

  • 以下类会编译吗?如果没有,为什么?

public class Singleton<T> {

    public static T getInstance() {
        if (instance == null)
            instance = new Singleton<T>();

        return instance;
    }

    private static T instance = null;
}
  • 给定以下类别:
class Shape { /* ... */ }
class Circle extends Shape { /* ... */ }
class Rectangle extends Shape { /* ... */ }

class Node<T> { /* ... */ }

以下代码可以编译吗?如果没有,为什么?

Node<Circle> nc = new Node<>();
Node<Shape>  ns = nc;
  • 考虑此类:
class Node<T> implements Comparable<T> {
    public int compareTo(T obj) { /* ... */ }
    // ...
}

以下代码可以编译吗?如果没有,为什么?

Node<String> node = new Node<>();
Comparable<String> comp = node;
  • 您如何调用以下方法在列表中查找相对于指定整数列表而言是素数的第一个整数?
public static <T>
    int findFirst(List<T> list, int begin, int end, UnaryPredicate<T> p)

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

检查一下你的答案。