一、定義一個簡單的“泛型”類
package tigers;
public class GenericIdentify {
public static void main(String[] args) {
Generic1 gStr = new Generic1();
gStr.set("aaaaaaaaaaaaaaaaa");
Generic1 gInt = new Generic1();
gInt.set(new Integer(1321423));
Generic1 gBool = new Generic1();
gBool.set(new Boolean(true));
System.out.println(gStr.get() + "\n" +
gInt.get() + "\n" +
gBool.get() + "\n");
((Generic1)gInt).set("bbbbbbbbbbbbb"); //避開類型檢查
System.out.println(gInt.get());
}
}
class Generic1 { //聲明泛型
private A a;
public void set(A a) {
this.a = a;
}
public A get() {
return this.a;
}
}
C:\tiger>javac -d c:\tiger\cls\ c:\tiger\src\*.Java
Note: c:\tiger\src\GenericIdentify.Java uses unchecked or unsafe Operations.
Note: Recompile with -Xlint:unchecked for details.
C:\tiger>Java -classpath c:\tiger\cls tigers.GenericIdentify
aaaaaaaaaaaaaaaaa
1321423
true
bbbbbbbbbbbbb
C:\tiger>