0

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

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>这样的回来可能会引起麻烦

4

1 回答 1

2

编译器不可能检查您读取的内容是 a Stack<Integer>、 aStack<String>还是 a Stack<Whatever>。所以最后,必须知道堆栈中有什么,你必须决定堆栈的类型。剩下的就是语法糖。

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

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

如果你把它写成

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

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

Stack<Integer> stack = readAll(path);

但最终,结果是一样的。如果从堆栈中获取 Integer 不是真正的Stack<Integer>.

于 2012-06-02T13:43:45.090 回答