学习自
https://www.cnblogs.com/coprince/p/8603492.html
泛型分类
- 类泛型
- 接口泛型
- 方法泛型
- 泛型通配符
类泛型
方法名后的为决定内部T,但是也可以初始化的时候不在方法名后申明这个T是什么,可以在其他地方声明,但是声明后这个泛型的类型就会确定
public class Genericity<T> {
T name;
Genericity(T name){
this.name=name;
}
public T getName(){
return name;
}
public void setId(T id){
System.out.println(id);
}
}
public class Test {
public static void main(String[] args) {
Genericity<Integer> genericity1 = new Genericity<Integer>(123);
Genericity<String> genericity2 = new Genericity<String>("hahaha");
Genericity genericity3 = new Genericity(456);
System.out.println(genericity1.getName());
System.out.println(genericity2.getName());
//genericity2.setId(123);
//这里会报错,因为之前已经把T定义为String类型,不可以再变
System.out.println(genericity3.getName());
}
}
输出结果
123
hahaha
456
泛型接口
跟泛型类相似,但是要在它的实现类中的方法名后加上
public interface IGenericity<T> {
public T getname();
}
public class Genericity_1<T> implements IGenericity<T> {
T name;
Genericity_1(T name){
this.name= name;
}
@Override
public T getname() {
return name;
}
}
public class Test {
public static void main(String[] args) {
IGenericity iGenericity = new Genericity_1("Genericity_1");
System.out.println(iGenericity.getname());
}
}
输出结果
Genericity_1
泛型通配符
用<?>表示,在泛型类中表示其他种类的泛型
public class Genericity<T> {
T name;
Genericity(T name){
this.name=name;
}
public T getName(){
return name;
}
public void setId(T id){
System.out.println(id);
}
public void showGenericity(Genericity<?> genericity){
System.out.println("genericity:"+genericity.getName());
}
public <T> T showGenericityname(Genericity<T> genericity2){
return genericity2.getName();
}
}
public class Test {
public static void main(String[] args) {
Genericity<Integer> genericity1 = new Genericity<Integer>(123);
Genericity<String> genericity2 = new Genericity<String>("hahaha");
Genericity genericity3 = new Genericity(456);
genericity1.showGenericity(genericity2);
}
}
genericity:hahaha
泛型方法
泛型方法中的泛型为一个新的泛型,如果他在泛型类中,即使跟泛型类中的泛型名称相同,也是一个单独全新的泛型
public class Genericity<T> {
T name;
Genericity(T name){
this.name=name;
}
public T getName(){
return name;
}
public void setId(T id){
System.out.println(id);
}
public void showGenericity(Genericity<?> genericity){
System.out.println("genericity:"+genericity.getName());
}
//泛型方法
public <E> E showGenericityname(Genericity<E> genericity2){
return genericity2.getName();
}
}
public class Test {
public static void main(String[] args) {
Genericity<Integer> genericity1 = new Genericity<Integer>(123);
Genericity<String> genericity2 = new Genericity<String>("hahaha");
Genericity genericity3 = new Genericity(456) System.out.println(genericity1.showGenericityname(genericity2));
}
}
hahaha
静态方法使用泛型,则必须要将泛型定义为泛型方法