A User
A User

Reputation: 375

Java Generic Serializable, Iterable Stack

The following is the snippet of my program to serialize and deserialize a generic stack
Deserialization Method

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;
}

Serialization Method

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

How data is serialized and deserialized

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);
        }
    }
}  

Question: Is the return type of the readAll() method really doing anything to provide flexibility or it won't matter if I change it to Stack<T> My logic was that there maybe chances that data that was written to the file maybe of Stack<Integer> so while reading it back it might cause troubles

Upvotes: 0

Views: 749

Answers (1)

JB Nizet
JB Nizet

Reputation: 692071

It's impossible for the compiler to check if what you read is a Stack<Integer>, a Stack<String>, or a Stack<Whatever>. So in the end, you have to know what is in the stack, and you have to decide the type of the stack. The rest is syntactic sugar.

If you leave it like that, and you know you're reading a Stack<Integer>, you'll have to write

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

If you write it as

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

the compiler can infer the type from the declaration of the variable, and you can thus write

Stack<Integer> stack = readAll(path);

But in the end, the result is the same. You'll get an exception when getting an Integer from the stack if it's not really a Stack<Integer>.

Upvotes: 2

Related Questions