gpt4 book ai didi

Java 通用可序列化、可迭代堆栈

转载 作者:行者123 更新时间:2023-12-02 07:45:57 24 4
gpt4 key购买 nike

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

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() 方法的返回类型是否真的做了任何事情来提供灵 active ,或者如果我将其更改为 Stack<T> 也没关系。我的逻辑是,写入文件的数据可能是 Stack<Integer>因此在读回它时可能会引起麻烦

最佳答案

编译器不可能检查你读到的内容是否是 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);

但最终的结果都是一样的。如果从堆栈中获取 Integer 不是真正的 Stack<Integer> ,则会出现异常.

关于Java 通用可序列化、可迭代堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10862694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com