java中的泛型

1.泛型的概述

是一种把明确类型的工作推迟到创建对象或者调用方法的时候才去明确的特殊的类型

2.格式

<数据类型> 只能是引用类型

3.好处

a:把运行时期的问题提前到了编译期间
b:避免了强制类型转换
c:优化了程序设计,解决了黄色警告线问题,让程序更安全

4.泛型的用法

a:泛型类

class  Demo{
   ObjectTool<String> otool = new ObjectTool<String>();
   otool.show("hello");//hello
}
class ObjectTool<T>{
   public void show(T t){
         Systemo.out.println(t);
}
}

b:泛型方法

class  Demo{
   ObjectTool otool = new ObjectTool();
   otool.show("hello");//hello
}
class ObjectTool{
   public <T> void show(T t){
         Systemo.out.println(t);
}
}

c:泛型接口a

class  Demo{
   Animal<String>  animal= new Dog();
   otool.show("hello");//hello
}
class Dog implements Animal<String>{
   public  void show(String str){
         Systemo.out.println(str);
   }
}
public interface Animal<T>{
   public  void show(T  t){
         Systemo.out.println(t);
   }
}

d:泛型接口b

class  Demo{
   Animal<String>  animal= new Dog<String>();
   otool.show("hello");//hello
}
class Dog<T> implements Animal<T>{
   public  void show(T  t){
         Systemo.out.println(t);
   }
}
public interface Animal<T>{
   public  void show(T  t){
         Systemo.out.println(t);
   }
}

e:泛型高级通配符 ?、? extends E、? super E

class  Demo{
//匹配所有
Collection<?>  collection1 = new ArrayList<Animal>();
Collection<?>  collection2 = new ArrayList<Dog>();
Collection<?>  collection3 = new ArrayList<Cat>();
Collection<?>  collection3 = new ArrayList<Object>();

//匹配 animal和animal的子类
Collection<? extends Animal>  collection1 = new ArrayList<Animal>();
Collection<? extends Animal>  collection2 = new ArrayList<Dog>();
Collection<? extends Animal>  collection3 = new ArrayList<Cat>();

//匹配 animal和animal的父类
Collection<? super Animal>  collection1 = new ArrayList<Animal>();
Collection<? super Animal>  collection2 = new ArrayList<Dog>();
Collection<? super Animal>  collection3 = new ArrayList<Cat>();
}
class Animal{ 
}
class Dog extends Animal{}
class Cat extends Animal{}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容