15-08
自訂的類中使用泛型,即為泛型類
class Worker{
}
class Student{
}
class Tool{
private Object obj;
public void setObject(Object obj){
this.obj=obj;
}
public Worker getObject(){
return obj;
}
}
//什麼時間來定義泛型類呢?
當類中要操作的引用資料類型不確定時
早期,定義Object來完成擴充
現在定義泛型來擴充
泛型的出現,不要再強轉啊
把錯誤存在了編譯時間
class Utils<QQ>{
private QQ q;
publi void setObject(QQ q){
this.q=q;
}
public QQ getObject(){
return q;
}
}
class GenericDemo3{
public static void main(String[] args){
Tool t=new Tool();
t.setObject(new Worker());
t.getObject();
Utils<Worker> u=new Utils<Worker>();
}
}
15-09泛型方法
class Demo<T>{
public void show(T t){
sop("show:"+t);
}
}
//泛型類的定義的泛型,在整個類中有效,若此法使用,
//那麼泛型類的對象一定要操作
class Demo{
public<T> void show(T t){
sop("show:"+t);
}
public <T> void print(Q q){
sop("print:"+t);
}
}
class GenericDemo{
public static void main(String[] args){
Demo<Integer> d=new Demo<Integer>();
d.show(new Integer(4));
d.show(9);
d.show("fdfdffd");//失敗了,若要操作字串,只能重新定義
Demo<String> b=new Demo<String>();
b.show("dddd");
b.show(5);//失敗了。
//__________________使用泛型方法
Demo d=new Demo();
d.show("dfdffd");
d.show(new Integer(4));
d.print("ffd");
}
}
15-10靜態方法泛型
15-11介面上
15-12泛型的進階使用
class GenericDemo6{
public static void main(String[] args){
ArrayList<String> al=new ArrayList<String>();
al.add("fdfd");
ArrayList<Integer> all=new ArrayList<Integer>();
all.add(4);
all.add(7);
all.add(1);
}
public static void print(ArrayList<String> al){
Integer<String> it=al.iterator();
while(it.hasnext()){
sop(it.next());
}
}
//此法,只能使用string, 不能用Integer.怎麼辦啊
呢??請使用?預留位置
public static void print(ArrayList<?> al){
Integer<?> it=al.iterator();
while(it.hasnext()){
sop(it.next());
}
}
法二
public static<T> void print(ArrayList<T> al){
Integer<T> it=al.iterator();
while(it.hasnext()){
T t=it.next();//此得可以操作的。。。。。
//sop(it.next().length());//此時?不能用
sop(it.next());
}
}
泛型限定,未聽會
?萬用字元:也可理解為預留位置
泛型的限定
?extends E:可以接收E類型或子類型
? super E:可以接收E類型或E的父類型