Java泛型

    xiaoxiao2021-12-14  20

      泛型,是类型,是参数化的类型,类似形参,其是jdk1.5之后后引入的,在具体使用的时候回传入具体的类型,但指定的类型必须是引用类型,若要使用基本数据类型,可以用类包装,如Integer。

    // 泛型类定义,同泛型接口,类似ArrayList<T>、List<T> // 泛型定义放在<>内,必须在类名之后,<>内字母表示不确定类型,多个字母用逗号间隔,通常用大写字母T、E、K、V来表示 public class GenericTest<K, V> { K k; V v; public GenericTest(K k, V v) { this.k = k; this.v = v; } // 泛型方法 // 泛型定义放在<>内,必须在限定符或static后、返回类型前 public <T> T sayHello(T t) { System.out.println("Hello " + t); return t; } public static void main(String[] args) { GenericTest<String, Integer> gt = new GenericTest<String, Integer>("ss", 1); gt.sayHello("test"); } }
    转载请注明原文地址: https://ju.6miu.com/read-963729.html

    最新回复(0)