一、起因:JDK1.4以前类型不明确
1、装入集合的类型都被当作Object对待,从而失去自己的实际类型。
2、从集合中取出时往往需要转型,效率低,容易产生错误。
3、方案:在定义集合的时候同时定义集合中对象的类型。
4、作用:
<1>、模板:提高代码的重用率。
<2>、安全:在编译的时候检查类型安全。
<3>、省心:所有的强制转换都是自动和隐式的。
二、概念:泛型就是参数化类型。
1、适用于多种数据类型执行相同功能的代码。
2、泛型中的类型在使用时指定。
3、泛型归根结底就是“模板”。
4、泛型主要适用于在集合中。
三、自定义泛型类的定义及注意事项。
package Gen泛型; /* * 自定义泛型类 * 1、<>--->单个大写字母,尽可能见名之意。 * 2、T Type * K V key value * E element * 3、注意点: * 1、泛型不能使用在静态属性上。 * 2、指定的类型不能为基本类型。 */ public class Student<T> { private T javase; public Student() { } public Student(T javase) { this.javase = javase; } public T getJavase() { return javase; } public void setJavase(T javase) { this.javase = javase; } } package Gen泛型; /* * 自定义泛型类的使用: * 1、在声明时指定具体的类型。 * 2、不能为基本类型。 */ public class MyStudent { public static void main(String[] args) { Student<Integer> stu = new Student<Integer>(); stu.setJavase(80); System.out.println(stu.getJavase()); } } 三、自定义泛型接口。
package Gen泛型; public interface Test<T> { int Value =1;//因为接口定义的常量默认是public static final,所以不能使用泛型。 T test(T t); }
package Gen泛型; import java.util.ArrayList; import java.util.List; public class Method { public static void main(String[] args) { test("123"); test(new ArrayList()); } /* * 泛型方法:在返回类型前加<T> */ public static <T> void test(T t){ System.out.println(1); System.out.println(t); } public static <T extends List> void test(T t){ //只能传递List类及它的子类 System.out.println(t); System.out.println(2); } }