Java范型广泛应用于容器类,如ArrayList<String>
即是一个使用泛化的例子,内部定义为ArrayList<T>
。
当然,大多数时候,范型是可以用Object代替的,相比Object,使用范型更加安全,编译器能对类型的检查更加完善。使用范型不需要使用cast,能在编译时就发现问题。
范型的简单例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// GenericType.java public class GenericType<T> { private T t; public GenericType(T t){ this.t = t; } public T getValue(){ return t; } } // Test.java public class Test { public static void main(String... args) { GenericType<String> gts = new GenericType<String>("Hello"); String value = gts.getValue(); GenericType<Integer> gti = new GenericType<Integer>(1); int number = gti.getValue(); } } |
上面是一个基本的例子,如果换用Object来实现,需要cast,并且可能发生ClassCastException异常。
同时,使用范型接口,能对实现类直接生成具体的类,下面是一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// GenericTypeInterface.java public interface GenericTypeInterface<T> { public T fun(T t); } // GenericTypeImpl.java public class GenericTypeImpl implements GenericTypeInterface<String> { @Override public String fun(String s) { // 能生成具体参数和返回值类型 return null; } } |
范型可以用来限制某些类才能合法使用方法:
List<? extends Fruit>
表示 List 中可以放置 Fruit 的子类, 如ArrayList<Apple>
或ArrayList<Orange>
List<? super Fruit>
表示 List 中可以放置任意 Fruit 的父类, 如ArrayList<Object>