问题与练习:泛型

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();
}
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 是最大公约数的缩写。

检查一下你的答案。

首页