1.泛型的概述
是一種把明確類型的工作推遲到創(chuàng)建對象或者調(diào)用方法的時候才去明確的特殊的類型
2.格式
<數(shù)據(jù)類型> 只能是引用類型
3.好處
a:把運行時期的問題提前到了編譯期間
b:避免了強制類型轉(zhuǎn)換
c:優(yōu)化了程序設(shè)計琢歇,解決了黃色警告線問題,讓程序更安全
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{}