本质是参数化类型,把类型座位参数传递,常见形式有:泛型类、泛型接口、泛型方法。
语法:<T, …> T成为类型占位符,表示一种引用类型(可以有多个,用逗号隔开)。
好处:
- 提高代码的重用性
- 防止类型转换异常,提高代码的安全性
泛型类
语法:类名<T>(可以有多个,用逗号隔开)
public class MyGeneric<T> {
//1.创建变量
T t;
//2.作为方法的参数
public void show(T t){
System.out.println(t);
}
//3.泛型作为方法的返回值
public T getT(){
return t;
}
}
public class Test {
public static void main(String[] args) {
//使用泛型类创建对象
//注意:泛型只能使用引用类型;不同泛型对象之间不能相互赋值
MyGeneric<String> myGeneric = new MyGeneric<String>();
myGeneric.t = "Hello";
myGeneric.show("Hello World!");
String str = myGeneric.getT();
System.out.println(str);
MyGeneric<Integer> myGeneric1 = new MyGeneric<Integer>();
myGeneric1.t = 100;
myGeneric1.show(200);
Integer integer = myGeneric1.getT();
System.out.println(integer);
}
}
泛型接口
语法:接口名<T>(可以有多个,用逗号隔开)
public interface MyInterface<T> {
//注意:不能用泛型创建静态常量
String str = "张三";
T server(T t);
}
//在实现类时直接确定好T所代指的引用类型
public class MyInterfaceImpl implements MyInterface<String>{
@Override
public String server(String t) {
System.out.println(t);
return t;
}
}
//也可以将实现类也设计为泛型类 则对应泛型接口时也要使用<T>
public class MyInterface2Impl<T> implements MyInterface2<T>{
@Override
public T server(T t) {
System.out.println(t);
return t;
}
}
public class Test {
public static void main(String[] args) {
MyInterfaceImpl impl = new MyInterfaceImpl();
impl.server("test1");
MyInterface2Impl<String> impl2 = new MyInterface2Impl<>();
impl2.server("test2");
}
}
泛型方法
语法:<T> 返回值类型
public class MyGenericMethod {
//泛型方法 - 这里的<T>的作用范围仅在当前方法内
public <T> void show(T t){
System.out.println("test" + t);
}
}
public class FanXing {
public static void main(String[] args) {
MyGenericMethod myGenericMethod = new MyGenericMethod();
//参数作为T,类型是由传入的类型决定的
myGenericMethod.show(100);
myGenericMethod.show("张三");
}
}
泛型集合
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致。
特点:
- 编译时即可检查,而非运行时抛出异常。
- 访问时,不必类型转换(拆箱)。
- 不同泛型之间引用不能相互赋值,泛型不存在多态。
在使用ArrayList这些集合的时候,可能会出现以下情况:
public class Demo1 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("test1");
arrayList.add("test2");
arrayList.add(10);//这里不会报错 - 因为元素确实添加到了集合中
for (Object object: arrayList) {//运行时报错
String str = (String)object;
System.out.println(str);
}
}
}
由于使用add添加元素时,元素的类型没有准确的限制,所以在某些情况下如果要使用,会因为不知道原类型而导致出错,使用泛型集合可以保证集合元素类型一致。
public class Demo2 {
public static void main(String[] args) {
ArrayList<String> arrayList2 = new ArrayList();
arrayList2.add("test1");
arrayList2.add("test2");
//arrayList2.add(10);//直接报错,因为使用了泛型集合,只能添加String类型的元素
for (String tmp: arrayList2) {
String str1 = tmp;
System.out.println(str1);
}
}
}
知识点整理自bilibili(千峰Java学习营)视频链接