1

假設serialise.bin是一個文件,是滿語的,被一個ArrayList時,它是序列化反序列化文件,然後將內容存儲在ArrayList <String>中。 (JAVA)

public static ArrayList<String> deserialise(){ 
    ArrayList<String> words= new ArrayList<String>(); 
    File serial = new File("serialise.bin"); 
    try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(serial))){ 
     System.out.println(in.readObject()); //prints out the content 
    //I want to store the content in to an ArrayList<String> 
    }catch(Exception e){ 
     e.getMessage(); 
    } 
return words; 
} 

我希望能夠deserialise了「serialise.bin」文件和存儲內容在一個ArrayList

+0

你的問題是什麼?你的代碼有問題嗎? – shmosel

+0

不要返回'ArrayList'。相反,返回List,這樣'deserialise'的調用者就不會依賴於那個實現細節。 –

回答

0

鑄造它ArrayList<String>,爲in.readObject()並返回一個Object,並將其分配給words

@SuppressWarnings("unchecked") 
public static ArrayList<String> deserialise() { 

    // Do not create a new ArrayList, you get 
    // it from "readObject()", otherwise you just 
    // overwrite it. 
    ArrayList<String> words = null; 
    File serial = new File("serialise.bin"); 

    try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(serial))) { 
     // Cast from "Object" to "ArrayList<String>", mandatory 
     words = (ArrayList<String>) in.readObject(); 
    } catch(Exception e) { 
     e.printStackTrace(); 
    } 

    return words; 
} 

註釋可以添加0來抑制類型安全警告。它會發生,因爲您必須將Object轉換爲通用類型。使用Java的類型擦除如果在運行時轉換是類型安全的,則無法知道編譯器。 Here是另一篇文章。此外e.getMessage();不做任何事,打印它或使用e.printStackTrace();

+0

感謝您的幫助,它的工作原理,但我必須添加一個「@SuppressWarnings(」unchecked「)」。我不確定這是什麼,但一旦它被添加,我不再收到關於「類型安全性:從對象到ArrayList 」的警告。「 –

+0

你是對的,你無法避免這個警告,只是壓制它。更新了答案。 – thatguy

+0

是@SupressWarnings(「unchecked」)好的代碼嗎?在這種情況下,我會保持它,因爲我可以想到另一種方式。 –

相關問題