示例代码:
package main; /** * 在类中 定义泛型 * * */ public class Genericity<T> { public T[] ts; private T t; public Genericity(T t, T[] ts) { super(); this.t = t; this.ts = ts; } public Genericity() { } public void setT(T t) { this.t = t; } public T getT() { return this.t; } } package main; public class Main { public static void main(String[] args) { // 创建泛型类的对象 Genericity<Integer> genericity = new Genericity<>(); genericity.setT(123); Integer t = genericity.getT(); System.out.println("t:"+t); Genericity<String> gen = new Genericity<>(); gen.setT("哈哈"); String str = gen.getT(); System.out.println("str="+str); } }2.2 实例化泛型类 实例化泛型类时,必须制定泛型的具体类型。例如: Test<String> test1 = new Test<String>(); 3 泛型运用在方法中 单独在方法中运用泛型: public <T> T test(T t) { // 方法中的T 由 实际参数的类型决定. return t; } 4 泛型中的 通配符 ? 通配符只能用在声明泛型类的引用,和定义泛型类返回值中: Test<?> test=new Test<Object>();//该引用可以指向 new Test<任意类型>(); public Test<?> getTest(){//可以返回 new Test<任意类型>(); return new Test<Object>(); } 5 泛型中使用 extends\super 1. extends 可以用在设计泛型,也能用在 声明泛型类的引用,和定义泛型类返回值中 2. super 不能用在设计泛型,只能用在 声明泛型类的引用,和定义泛型类返回值中
设计两个类Student类和People类,Student类继承People类
如:设计泛型类时 public class Test<K extends Student>{} //正确 public <T extends People> void text(T t) {//正确 } public class Test<K super Student>{} //错误 public <T super Student> void text(T t) {//错误 } 如:声明泛型类的引用,和定义泛型类返回值中 //声明泛型类的引用 Test<? extends People> test = new Test<Student>(); //定义泛型类返回值 public Test<? extends People> getTest(){ return new Test<Student>(); } // 正确 //声明泛型类的引用 Test<? super Student> test = new Test<People>(); //定义泛型类返回值 public Test<? super Student> getTest(){ return new Test<People>(); } // 正确