2012-05-11 216 views
1

這是我的方法爪哇 - 鑄造類型列表陣列

public AuctionItem[] getOpenAuctions() throws RemoteException { 

    return itemList.toArray((AuctionItem[]) java.lang.reflect.Array 
      .newInstance(itemList.getClass(), itemList.size())); 

} 

,這是我的錯誤

Exception in thread "main" java.lang.ClassCastException: [Ljava.util.LinkedList; cannot be cast to [LAuction.AuctionItem; 
at Auction.AuctionImpl.getOpenAuctions(AuctionImpl.java:44) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
at java.lang.reflect.Method.invoke(Unknown Source) 
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source) 
at sun.rmi.transport.Transport$1.run(Unknown Source) 
at sun.rmi.transport.Transport$1.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at sun.rmi.transport.Transport.serviceCall(Unknown Source) 
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source) 
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source) 
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) 
at java.lang.Thread.run(Unknown Source) 
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source) 
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source) 
at sun.rmi.server.UnicastRef.invoke(Unknown Source) 
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(Unknown Source) 
at java.rmi.server.RemoteObjectInvocationHandler.invoke(Unknown Source) 
at $Proxy0.getOpenAuctions(Unknown Source) 
at Seller.SellerMain.main(SellerMain.java:38) 

這有什麼錯呢?

回答

6

嘗試:

return itemList.toArray(new AuctionItem[itemList.size()]); 

的代碼你寫的問題是,itemList.getClass()返回類LinkedList。因此,Array.newInstance()方法創建了一個LinkedList[],然後您嘗試將其轉換爲AuctionItem[]。由於這兩種類型不兼容分配,因此會拋出ClassCastException

1

itemList.getClass()返回LinkedList.class,因爲它是一個LinkedList。 itemList.peek().getClass()會解決這個問題,但只有當列表中至少有一個元素。

爲什麼不乾脆:

public AuctionItem[] getOpenAuctions() { 
    return itemList.toArray(new AuctionItem[itemList.size()]); 
}