1 2 3 4 下一页 一、定义一个简单的“泛型”类 package tigers; public class GenericIdentify { public static void main(String[] args) { Generic1<String> gStr = new Generic1<String>(); gStr.set("aaaaaaaaaaaaaaaaa"); Generic1<Integer> gInt = new Generic1<Integer>(); gInt.set(new Integer(1321423)); Generic1<Boolean> gBool = new Generic1<Boolean>(); 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<A> { //声明泛型 private A a; public void set(A a) { this.a = a; } public A get() { return this.a; } }
C:tiger>Javac -d c:tigercls c:tigersrc*.java Note: c:tigersrcGenericIdentify.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. C:tiger>java -classpath c:tigercls tigers.GenericIdentify aaaaaaaaaaaaaaaaa 1321423 true bbbbbbbbbbbbb (责任编辑:admin) |