问题和练习:泛型
原文: https://docs.oracle.com/javase/tutorial/java/generics/QandE/generics-questions.html
编写一个通用方法来计算集合中具有特定属性的元素数(例如,奇数整数,素数,回文数)。
下面的类会编译吗?如果没有,为什么?
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 是最大公约数的缩写。
