使用object表示泛型

来源:互联网 发布:淘宝加工厂 编辑:程序博客网 时间:2024/09/21 09:29

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);}}



0 0
原创粉丝点击