https://www.jianshu.com/p/986f732ed2f1
泛型是指把类型参数化,在使用的时候再把数据类型确定下来
一些常用的泛型类型变量:
E:元素(Element),多用于java集合框架
K:关键字(Key)
N:数字(Number)
T:类型(Type)
V:值(Value)
1.泛型类
public class Person<T>{
private T date;
public T getData(){
return date;
}
public void setData(T data){
this.data = data;
}
}
2.泛型接口
public interface InterfaceName<T>{
T getData();
}
实现接口时可以选择指定范型类型,也可以不指定
1.指定类型
public class Interface1 implements InterfaceName<String>{
private String text;
@Override
public String getData(){
return text;
}
}
2.不指定类型
public class Interface2<T> implement InfaceName<T>{
private T data;
@Override
public T getData(){
return data;
}
}
3.泛型方法
public static <T> T fun(T a, T b){}
4.泛型限制类型
使用泛型时可以指定泛型的区域
<T extends 类或者接口1 & 接口2>
限定类型必须是某种类的子类或者某个接口实现类
5.泛型中的通配符?
(1)<? extends Parent> 指定了泛型类型的上届
(2)<? super Child> 指定了泛型类型的下届
(3) <?> 指定了没有限制的泛型类型

public class Demo{
public static void main(String[] args){
// 这个Furit不理解的可以看这个例子
// Furit就是引用变量furit的类型
Furit furit = new Furit()
// 不可以将装着水果的盘子看作装着苹果的盘子
// 这个Plate p其实就是一个Furit p
Plate<Furit> p = new Plate<Apple>()
// 传入的泛型必须是Furit的子类
Plate<? extends Furit> p = new Plate<Apple>()
}
}
interface Furit{}
class Apple implements Furit{}
class Plate<T>{
T data;
}
作用:
1、 提高代码复用率
2、 泛型中的类型在使用时指定,不需要强制类型转换(类型安全,编译器会检查类型)
泛型在实际使用中举例
public class Demo4 {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(112);
al.add(123);
al.add(121);
al.add(122);
al.add(1);
String s = "12";
Object s1 = 12;
String s2 = String.valueOf(s1);
al.add(s2);
System.out.println(fun(al, s));
}
public static boolean fun(ArrayList<String> al, String s){
boolean flag = false;
if (al.contains(s)){
flag = true;
}
return flag;
}
}
如上图所示,在创建ArrayList对象时我们并没有使用泛型,所以实际在添加元素时可以是String或者int它都不会报错,但是可以看到我在使用fun( )方法时,实际已经规定了要是String,在写代码的过程中,我默认了添加的是String类型,但是实际却添加了int类型,但是它不会报错提醒我,在使用泛型之后其实是有一个帮你检验代码的作用
本文深入讲解Java泛型的五大核心概念:泛型类、泛型接口、泛型方法、泛型限制类型及泛型中的通配符。通过实例演示如何在类、接口和方法中应用泛型,以及如何使用泛型限制和通配符增强代码灵活性和安全性。
349

被折叠的 条评论
为什么被折叠?



