0

編譯Java類時出現以下錯誤:BlueJJava未經檢查或不安全操作消息

try { 
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(Filename)); 
    ArrayList<AuctionItem> AuctionList = (ArrayList<AuctionItem>) in.readObject(); 
    in.close(); 
} 
catch (Exception e) { 
    e.printStackTrace(); 
} 

我可以請有一些信息,爲什麼被顯示此錯誤,並且一些幫助:

AuctionManager.java uses unchecked or unsafe operations. 

當下面的反序列化的代碼是在我的一個功能時,纔會顯示此錯誤使用沒有錯誤的反序列化代碼。

回答

1

首先你得到的信息不是錯誤,是不是一個警告;它不會阻止您編譯或運行程序。

至於源,它是這一行:

ArrayList<AuctionItem> AuctionList = (ArrayList<AuctionItem>) in.readObject();

由於正在鑄造的對象(readObject返回Object)到參數化的類型(ArrayList<AuctionItem>)。

+0

什麼是修復代碼的最佳方法,以便警告不顯示? – user2351151 2013-05-13 04:55:59

1

user2351151:你能做到這一點的警告不會顯示:

ArrayList tempList; // without parameterized type 
try { 
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(Filename)); 
    tempList = (ArrayList) in.readObject(); 
    for (int i = 0; i < tempList.size(); i++) { 
    AuctionList.add(i, (AuctionItem)tempList.get(i)); // explict type conversion from Object to AuctionItem 
    } 
    in.close(); 
} 
catch (Exception e) { 
    e.printStackTrace(); 
} 

您必須重寫用顯式類型轉換的ArrayList(你可以不使用參數化類型的ArrayList臨時)。