【发布时间】: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<Auction> auctions; -
您是否尝试将其转换为
(List<Action>)而不是(ArrayList<Auction>)?
标签: java list exception collections synchronization