设计存储单元
存储单元如果也能说是一种ADT的话,那应该具有的基本功能我认为是两个:
- 存/写入
- 取/读出
初始化的时候可以按照默认的来,也可以指定具体的initialValue。
据此,将其抽象成一个类就可以实现了。
泛型类MemoryCell<T>的实现
public class MemoryCell<T> {
private T storedValue;
public MemoryCell() {}
public MemoryCell(T storedValue) {
this.storedValue = storedValue;
}
public T read() {
return storedValue;
}
public void write(T x) {
storedValue = x;
}
}
功能测试
public class MemoryCellTest {
public static void main(String [] args) {
MemoryCell<Integer> cell = new MemoryCell<>(7);
System.out.println("Contents are: " + cell.read());
cell.write(5);
System.out.println("Contents are: " + cell.read());
}
}
这里用一个int做了测试,如我们所愿:
Contents are: 7
Contents are: 5