可以从文件中读取对象来转换Collections.synchronizedList()吗?

时间:2016-10-20 22:18:34

标签: java list exception collections synchronization

我想从之前保存该列表的文件中读取Collections.synchronizedList(ArrayList<>())(即使可能吗?)。我收到了这个错误:

Exception in thread "main" java.lang.ClassCastException: java.util.Collections$SynchronizedRandomAccessList cannot be cast to java.util.ArrayList
    at RMIServerImpl.loadAuctions(RMIServerImpl.java:247)
    at RMIServerImpl.rmiStart(RMIServerImpl.java:293)
    at RMIServerImpl.main(RMIServerImpl.java:323)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

我的代码:

private List<User> users;

public RMIServerImpl() throws java.rmi.RemoteException{
    super();
    auctions = Collections.synchronizedList(new ArrayList<>()); 
}
public void saveAuctions(){
    ObjectFile file = new ObjectFile();
    try {
        file.openWrite("auctions");
    } catch (IOException e) {
        System.out.println("Problem opening auctions file(WRITE MODE).");
    }
    try {
        file.writeObject(this.auctions);
    } catch (IOException e) {
        System.out.println("Problem saving auctions");
    }
    try {
        file.closeWrite();
    } catch (IOException e) {
        System.out.println("Problem close auctions file(WRITE MODE).");
    }
}
public void loadAuctions(){
    ObjectFile file = new ObjectFile();
    try {
        file.openRead("auctions");
    } catch (IOException e) {
        System.out.println("Problem opening auctions file(READ MODE)(No auctions found)");
    }

    try {
        this.auctions= (ArrayList<Auction>) file.readObject();//PROBLEM OCCURS HERE
    } catch (IOException | ClassNotFoundException e) {
        System.out.println("Problem loading auctions");
    }

    try {
        file.closeRead();
    } catch (IOException e) {
        System.out.println("Problem closing auctions file(READ MODE)");
    }
}

1 个答案:

答案 0 :(得分:0)

将它转换为(List)而不是(ArrayList)解决了它