文档

Java™ 教程
教程: 学习 Java 语言
课程: 泛型(已更新)
首页 > 学习Java语言 > 泛型(已更新)

问题和练习的答案:泛型

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

    答案
    public final class Algorithm {
        public static <T> int countIf(Collection<T> c, UnaryPredicate<T> p) {
    
            int count = 0;
            for (T elem : c)
                if (p.test(elem))
                    ++count;
            return count;
        }
    }
    
    其中通用的 UnaryPredicate 接口定义如下:
    public interface UnaryPredicate<T> {
        public boolean test(T obj);
    }
    
    例如,以下程序计算整数列表中奇数整数的数量:
    import java.util.*;
    
    class OddPredicate implements UnaryPredicate<Integer> {
        public boolean test(Integer i) { return i % 2 != 0; }
    }
    
    public class Test {
        public static void main(String[] args) {
            Collection<Integer> ci = Arrays.asList(1, 2, 3, 4);
            int count = Algorithm.countIf(ci, new OddPredicate());
            System.out.println("奇数整数的数量 = " + count);
        }
    }
    
    程序输出:
    奇数整数的数量 = 2
    
  2. 以下类是否会编译?如果不会,为什么?
    public final class Algorithm {
        public static <T> T max(T x, T y) {
            return x > y ? x : y;
        }
    }
    
    答案:不会。大于号 (>) 运算符只适用于原始数值类型。
  3. 编写一个通用方法来交换数组中两个不同元素的位置。

    答案
    public final class Algorithm {
        public static <T> void swap(T[] a, int i, int j) {
            T temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }
    
  4. 如果编译器在编译时擦除所有类型参数,为什么应该使用泛型?

    答案:应该使用泛型,因为:
    • Java编译器可以在编译时对泛型代码进行更严格的类型检查。
    • 泛型支持将类型作为参数进行编程。
    • 泛型使您能够实现通用算法。
  5. 以下类在类型擦除后转换为什么?
    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 class Pair {
    
        public Pair(Object key, Object value) {
            this.key = key;
            this.value = value;
        }
    
        public Object getKey()   { return key; }
        public Object getValue() { return value; }
    
        public void setKey(Object key)     { this.key = key; }
        public void setValue(Object value) { this.value = value; }
    
        private Object key;
        private Object value;
    }
    
  6. 以下方法在类型擦除后转换为什么?
    public static <T extends Comparable<T>>
        int findFirstGreaterThan(T[] at, T elem) {
        // ...
    }
    
    答案:
    public static int findFirstGreaterThan(Comparable[] at, Comparable elem) {
        // ...
        }
    
  7. 以下方法会编译吗?如果不会,为什么?
    public static void print(List<? extends Number> list) {
        for (Number n : list)
            System.out.print(n + " ");
        System.out.println();
    }
    
    答案: 会。

  8. 编写一个通用方法,在列表的范围[begin, end)中找到最大元素。

    答案:
    import java.util.*;
    
    public final class Algorithm {
        public static <T extends Object & Comparable<? super T>>
            T max(List<? extends T> list, int begin, int end) {
    
            T maxElem = list.get(begin);
    
            for (++begin; begin < end; ++begin)
                if (maxElem.compareTo(list.get(begin)) < 0)
                    maxElem = list.get(begin);
            return maxElem;
        }
    }
    
  9. 以下类会编译吗?如果不会,为什么?
    public class Singleton<T> {
    
        public static T getInstance() {
            if (instance == null)
                instance = new Singleton<T>();
    
            return instance;
        }
    
        private static T instance = null;
    }
    
    答案: 不会。你不能创建类型参数T的静态字段。

  10. 给定以下类:
    class Shape { /* ... */ }
    class Circle extends Shape { /* ... */ }
    class Rectangle extends Shape { /* ... */ }
    
    class Node<T> { /* ... */ }
    
    以下代码会编译吗?如果不会,为什么?
    Node<Circle> nc = new Node<>();
    Node<Shape>  ns = nc;
    
    答案: 不会。因为Node<Circle>不是Node<Shape>的子类型。

  11. 考虑以下类:
    class Node<T> implements Comparable<T> {
        public int compareTo(T obj) { /* ... */ }
        // ...
    }
    
    以下代码会编译吗?如果不会,为什么?
    Node<String> node = new Node<>();
    Comparable<String> comp = node;
    
    答案: 会。
  12. 如何调用以下方法来查找列表中与指定整数列表互质的第一个整数?
    public static <T>
        int findFirst(List<T> list, int begin, int end, UnaryPredicate<T> p)
    
    注意,如果gcd(a,b)= 1,则两个整数ab是互质的,其中gcd表示最大公约数。

    答案
    import java.util.*;
    
    public final class Algorithm {
    
        public static <T>
            int findFirst(List<T> list, int begin, int end, UnaryPredicate<T> p) {
    
            for (; begin < end; ++begin)
                if (p.test(list.get(begin)))
                    return begin;
            return -1;
        }
    
        // x > 0 and y > 0
        public static int gcd(int x, int y) {
            for (int r; (r = x % y) != 0; x = y, y = r) { }
                return y;
        }
    }
    
    泛型UnaryPredicate接口定义如下:
    public interface UnaryPredicate<T> {
        public boolean test(T obj);
    }
    
    以下程序测试findFirst方法:
    import java.util.*;
    
    class RelativelyPrimePredicate implements UnaryPredicate<Integer> {
        public RelativelyPrimePredicate(Collection<Integer> c) {
            this.c = c;
        }
    
        public boolean test(Integer x) {
            for (Integer i : c)
                if (Algorithm.gcd(x, i) != 1)
                    return false;
    
            return c.size() > 0;
        }
    
        private Collection<Integer> c;
    }
    
    public class Test {
        public static void main(String[] args) throws Exception {
    
            List<Integer> li = Arrays.asList(3, 4, 6, 8, 11, 15, 28, 32);
            Collection<Integer> c = Arrays.asList(7, 18, 19, 25);
            UnaryPredicate<Integer> p = new RelativelyPrimePredicate(c);
    
            int i = Algorithm.findFirst(li, 0, li.size(), p);
    
            if (i != -1) {
                System.out.print(li.get(i) + "与");
                for (Integer k : c)
                    System.out.print(k + " ");
                System.out.println("互质");
            }
        }
    }
    
    该程序输出:
    11与7 18 19 25互质
    

上一页: 问题和练习:泛型