java的基本思想就是通过使用像object这样适当的超类实现泛型类
package chapter1;
class MemoryCell {
private Object storedValue;
public Object read() {
return storedValue;
}
public void write(Object x) {
storedValue = x;
}
}
public class Demo3 {
public static void main(String[] args) {
MemoryCell m = new MemoryCell();
m.write(new Integer(37));
Integer wrapperVal = (Integer) m.read();
int val = wrapperVal.intValue();
System.out.println("Contents are:" + val);
m.write("37");
String val2 = (String) m.read();
System.out.println("contents are:" + val2);
}
}
package chapter1;
class Gen<T> {
private T ob; // 定义泛型成员变量
public Gen(T ob) {
this.ob = ob;
}
public T getOb() {
return ob;
}
public void showType() {
System.out.println("T的实际类型是: " + ob.getClass().getName());
}
}
public class Demo3 {
public static void main(String[] args) {
// 定义泛型类Gen的一个Integer版本
Gen<Integer> intOb = new Gen<Integer>(88);
intOb.showType();
int i = intOb.getOb();
System.out.println("value= " + i);
System.out.println("----------------------------------");
// 定义泛型类Gen的一个String版本
Gen<String> strOb = new Gen<String>("Hello Gen!");
strOb.showType();
String s = strOb.getOb();
System.out.println("value= " + s);
}
}