泛型
泛型
- JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递
- 常见形式:泛型类,泛型接口,泛型方法
- 语法:<T,....> T称为类型占位符,表示一种引用类型
- 好处:提高代码的重用性;防止类型转换异常,提高代码的安全性
泛型类:
package com.java.leetcode.collection; /* 泛型类 语法:类名<T> T是类型占位符,表示一种引用类型,可以写多个 */ public class MyGeneric<T> { //使用泛型 //1.创建变量 T t; //2.作为方法的参数 public void show(T t){ //不能T t = new T(); System.out.println(t); } //3.泛型作为方法的返回值 public T getT(){ return t; } } class TestGeneric{ public static void main(String[] args) { //使用泛型类创建对象 //注意:1.泛型只能使用引用类,2.不同泛型对象不能互相赋值。如: MyGeneric<Integer> myGeneric2 = myGeneric 是不可以的。 MyGeneric<String> myGeneric = new MyGeneric<String>(); myGeneric.t = "hello"; myGeneric.show("我在学习泛型。"); String str = myGeneric.getT(); System.out.println(str); } }
运行结果;
泛型接口:
package com.java.leetcode.collection; /* 泛型接口 语法:接口名<T> 不能泛型静态常量 */ public interface MyInterface<T> { String name = "张三"; T server(T t); //参数类型和返回值类型都是T } //实现类方式一 class TestMyInterface implements MyInterface<String>{ @Override public String server(String s) { System.out.println(s); return s; } public static void main(String[] args) { TestMyInterface tm = new TestMyInterface(); tm.server("哈哈"); } } //实现类方式二 可在实例化的时候再确定类型 class TestMyInterface2<T> implements MyInterface<T>{ @Override public T server(T t) { System.out.println(t); return null; } public static void main(String[] args) { TestMyInterface2<Integer> tm = new TestMyInterface2<>(); tm.server(100); TestMyInterface2<String> tms = new TestMyInterface2<>(); tms.server("我是String"); } }
泛型方法:
package com.java.leetcode.collection; /* 泛型方法 语法:<T> 返回值类型 */ public class MyGenericMethod { //泛型方法 public <T> T show(T t){ System.out.println("泛型方法==>"+t); return t; } public static void main(String[] args) { MyGenericMethod mm = new MyGenericMethod(); mm.show("传递字符串"); mm.show(100); //传递的数据是什么类型,show方法中的T就是什么类型 } }
运行结果:
泛型集合:
概念:参数化类型,类型安全的集合,强制集合元素的类型必须一致
特点:
- 编译时即可检查,而非运行时抛出异常
- 访问时,不必类型转换(拆箱)
- 不同泛型之间引用不能互相赋值,泛型不存在多态