Java泛型
泛型类
即把不确定的数据元素类型用一个泛型占位符表示@Data
public class Person {
private T name;
private T address;
}Person person= new Person<>();
person.setName("attack204");
System.out.println(person.getName());
多类型泛型
即需要传递多个类型占位符,一个常见的应用是map@Data
public class MyMap {
private K key;
private V value;
public void setKeyAndValue(K key, V value) {
this.key = key;
this.value = value;
}
}MyMap myMap = new MyMap<>();
myMap.setKeyAndValue("attack204", 2333);
System.out.println(myMap.getKey());
System.out.println(myMap.getValue());
普通方法泛型@Data
public class Person {
private T name;
private T address;
//以下两种方法都可以
public String show(T inputName) {
return inputName + "is showing";
}
public String show2(E input) {
return input + "is showing two";
}
}Person person = new Person<>();
System.out.println(person.show("attack204"));
System.out.println(person.show2("attack203"));
静态方法泛型@Data
public class Person {
private T name;
private T address;
//注意,静态方法只能调用静态变量,T不是静态变量
//因此不能写成 public static String show(T inputName) {
public static String show(E inputName) {
return inputName + "is showing";
}
}System.out.println(Person.show("attack204"));
泛型接口
和上面差不多一样interfacepublic interface PersonInt {
public String show(T name);
}implementpublic class PersonImpl implements PersonInt {
@Override
public String show(String name) {
return name + "is showing three";
}
}
或者public class PersonImpl implements PersonInt {
@Override
public String show(T name) {
return name + "is showing three";
}
}mainPersonImpl person = new PersonImpl();
System.out.println(person.show("attack204"));
或者PersonImpl person = new PersonImpl<>();
System.out.println(person.show("attack204"))
擦除模式定义:java中的泛型只存在于编译阶段,在反射阶段会被擦除。
考虑这样一段代码Person p = new Person<>();
Person p1 = new Person<>();
system.out.println(p == p1);
//true目的:为了兼容低版本的jdk
通配符
在泛型中不识别父子继承关系(具体见视频)
因此需要通配符>来解决此错误
上边界与下边界
用了>相当于此处可以是任意类型,但是有时候需要对其进行限定
extends T>表示只能传入T及其子类,需要读取,但不写入时使用
super T> 表示只能传入T及其父类,需要写入,但不读取时使用