【问题标题】:Its possible to cast an Collections.synchronizedList() from object read from file?可以从从文件读取的对象中转换 Collections.synchronizedList() 吗?
【发布时间】:2016-10-20 22:18:34
【问题描述】:

我想从我之前保存该列表的文件中读取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)");
    }
}

【问题讨论】:

  • Collections.synchronizedList 不返回 ArrayList,它返回可以包装它的列表,但它不是 ArrayList 本身,也不是扩展它。
  • 你正在阅读的文件怎么样?
  • 这是一个目标文件,我保存我的拍卖列表。
  • 拍卖定义为:private List&lt;Auction&gt; auctions;
  • 您是否尝试将其转换为 (List&lt;Action&gt;) 而不是 (ArrayList&lt;Auction&gt;)

标签: java list exception collections synchronization


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-01
    • 2010-10-13
    • 1970-01-01
    • 2023-03-29
    • 2011-09-26
    • 2011-01-25
    相关资源
    最近更新 更多