java 泛型

xiaoxiao2021-02-28  97

1 什么是泛型? 泛型,即“参数化类型”。一提到参数,最熟悉的就是定义方法时有形参,然后调用此方法时传递实参。那么参数化类型怎么理解呢?顾名思义,就是将类型由原来的具体的类型参数化,类似于方法中的变量参数,此时类型也定义成参数形式(可以称之为类型形参),然后在使用/调用时传入具体的类型(类型实参)。 2 泛型的使用 2.1 泛型运用在 class 中        [访问修饰符]  class 类名<泛型1,泛型2,…>{           [访问权限] 泛型类型标识  变量名称;      [访问权限] 构造方法([<泛型类型>] 参数名称){ //内部代码}           [访问权限] 返回值类型 方法名称(){//内部代码 }           [访问权限] 返回值类型声明 方法名称(泛型类型标识 变量名称){ //内部代码}        }          例如:     /*       此处声明了一个包含泛型T的泛型类,T代表所有可能的类型,而T       的实际类型在 Test 类实例化时指定。      */    public class Test<T> { private T f; //f为泛型成员。在类名后面声明泛型后,在类内部可以向普通类型一样使 public Test(){ } //用泛型 public Test(T f){ this.f = f; } public void setF(T f) {//setF方法的参数类型为泛型T this.f = f; } public T getF() {//getF方法的返回类型为泛型T return f; } }

示例代码:

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>(); } // 正确
转载请注明原文地址: https://www.6miu.com/read-63058.html

最新回复(0)