使用Object表示泛型

来源:互联网 发布:帽子品牌知乎 编辑:程序博客网 时间:2024/06/03 15:45

Java中的基本思想就是可以通过使用像Object这样适当的超类来实现泛型类。

// MemoryCell class// Object read()        -->     Returns the stored value// void write()         -->     x is storedpublic class MemoryCell {    private Object storedValue;    public Object read() {        return storedValue;    }    public void write(Object x) {        storedValue = x;    }}

使用这种策略,必须要考虑两个细节:
1、读出对象时必须强制转换成正确类型

    MemoryCell memoryCell = new MemoryCell();    memoryCell.write("abc");    String str = (String) memoryCell.read();

2、不能传入基本类型,因为只有引用类型能够与Object相容

    MemoryCell memoryCell = new MemoryCell();    memoryCell.write(new Double(3.1415926));
0 0
原创粉丝点击