2012-06-02 28 views
0

以下是我的程序序列化和反序列化一般堆棧
反序列化方法的片段Java的通用串行化,可迭代堆棧

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>也許因此而回讀它可能會造成麻煩

回答

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

但是最後,r esult是一樣的。如果它不是真的Stack<Integer>,則從堆棧獲得Integer時會發生異常。

+0

這裏:'公衆堆棧 readAll(Path aPath){...}'''下面公共沒有必要嗎? –

+0

是的。否則該方法將不是一個通用的方法,編譯器會搜索一個名爲T的具體類。 –

+0

以及我的方法'public stack readAll(Path aPath)''我不需要''因爲它是一個通配的權利?只有當它是'公共堆棧 readAll(Path aPath)''我需要一個'' –