转自:http://blog.csdn.net/u014723123/article/details/38016957
术语:
递归类型限制:通过某个包含该类型参数本身的表达式来限制类型参数。
考虑如下的方法,它的作用是返回两个集合的联合:
- // Users raw types - unaccepable!
- public static Set union(Set s1, Set s2) {
- Set result = new HashSet(s1);
- result.addAll(s2);
- return result;
- }
- // Generic method
- public static <E> Set<E> union(Set<E> s1, Set<E> s2) {
- Set<E> result = new HashSet<E>(s1);
- result.addAll(s2);
- return result;
- }
泛型方法的一个显著特征是,无需明确指定类型参数的值,不像调用泛型构造器的时候是必须要指定类型参数的,在为泛型方法的类型会存在一个类型推导的过程。编译器通过检查方法参数的类型来计算类型的值。在调用 泛型构造器的时候,要明确传递类型参数的值可能有点麻烦。类型参数出现在了变量的声明的左右两边,显得冗余:
- // Parameterized type instance creation with constructor
- Map<String, List<String>> anagrams =
- new HashMap<String, List<String>>();
- // Generic static factory method
- public static <K, V> HashMap<K, V> newHashMap() {
- return new HashMap<K, V>();
- }
有时会需要创建不可变但是又适合于许多不同类型的对象,由于泛型是通过擦除来实现的,可以给所有的必要的类型参数使用同一个单个对象,但是需要一个静态的工厂方法来给每个必要的类型参数分发对象。这种模式叫做“泛型单例工厂”,这种模式最常用于函数的对象。假设有一个接口,描述了一个方法,该方法接受和返回某个类型T的值:
- public interface UnaryFunction<T> {
- T apply(T arg);
- }
- // Generic singleton factory pattern
- private static UnaryFunction<Object> INDENTITY_FUNCTION =
- new UnaryFunction<Object> {
- public Object apply(Object arg) { return arg; }
- };
- // IDENTITY_FUNCTION is stateless and its type parameter is
- // unbounded so it's safe to share one instance across all types.
- @SuppressWarnings("unchecked")
- public static <T> UnaryFunction<T> indentityFunction() {
- return (UnaryFunction<T>)INDENTITY_FUNCTION;
- }
- // Using a recursive type bound to express mutual comparability
- public static <T extends Comparable<T>> T max(List<T> list) {
- ...
- }
总之,泛型方法就像泛型一样,使用起来比要求客户端转换输入参数并返回值的方法来的更加安全,也更加容易。就像类型一样,你应该确保新的方法可以不用转换就能使用,这通常意味着要将它们泛型化。并且就像类型一样,还应该将现有的方法泛型化,使新用户使用起来更加轻松,且不会破坏现有的客户端。