Java Generic Serializable,Iterable Stack

时间:2012-06-02 13:33:01

标签: java generics serialization stack

以下是我的程序片段,用于序列化和反序列化通用堆栈
反序列化方法

public Stack<?> readAll(Path aPath){
    Stack<?> temp = new Stack<>();
    try(ObjectInputStream readStream = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(aPath)))) {
        temp = (Stack<?>) readStream.readObject();
    }catch(EOFException e) {
        e.printStackTrace();
        System.out.println("EOF");
    }catch(IOException | ClassNotFoundException e) {
        e.printStackTrace();
        System.exit(1);
    }
    return temp;
}

序列化方法

public void writeAll(Path aPath) {
    try(ObjectOutputStream writeStream = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(aPath)))) {
        writeStream.writeObject(this);
    }catch(IOException e) {
    e.printStackTrace();
    }
}  

如何序列化和反序列化数据

import java.nio.file.*;
public class StackTrial {
    public static void main(String[] args) {
        String[] names = {"A","B","C","D","E"};
        Stack<String> stringStack = new Stack<>(); //Stack that will be Serialized
        Stack<String> readStack = new Stack<>(); //Stack in which data will be read
        Path aPath = Paths.get("C:/Documents and Settings/USER/Beginning Java 7/Stack.txt");//Path of file

        for(String name : names) { //pushing data in
            stringStack.push(name);
        }

        for(String a : stringStack) { //displaying content
            System.out.println(a);
        }
        stringStack.writeAll(aPath); //Serialize
        readStack = (Stack<String>) readStack.readAll(aPath);//Deserialize

        for(String a : readStack) { //Display the data read
            System.out.println(a);
        }
    }
}  

问题: readAll()方法的返回类型是否真的可以提供灵活性,或者如果我将其更改为Stack<T>则无关紧要 我的逻辑是,有可能写入文件的数据可能是Stack<Integer>,所以在阅读它时可能会引起麻烦

1 个答案:

答案 0 :(得分:2)

编译器无法检查您所读取的内容是Stack<Integer>Stack<String>还是Stack<Whatever>。所以最后,必须知道堆栈中的内容,并且你必须决定堆栈的类型。其余的都是语法糖。

如果你这样离开,并且你知道你正在阅读Stack<Integer>,你将不得不写

Stack<Integer> stack = (Stack<Integer>) readAll(path);

如果你把它写成

public <T> Stack<T> readAll(Path aPath) {...}

编译器可以从变量的声明中推断出类型,因此可以编写

Stack<Integer> stack = readAll(path);

但最终,结果是一样的。如果它不是真正的Stack<Integer>,那么从堆栈中获取Integer时会遇到异常。