Chobeat
Chobeat

Reputation: 3535

Java - Casting typed list to array

This is my method

public AuctionItem[] getOpenAuctions() throws RemoteException {

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

}

and this is my error

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)

What's wrong with it?

Upvotes: 1

Views: 517

Answers (2)

FThompson
FThompson

Reputation: 28687

itemList.getClass() returns LinkedList.class, because it is a LinkedList. itemList.peek().getClass() would fix this, but only if the list has at least one element.

Why not just:

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

Upvotes: 1

Erick Robertson
Erick Robertson

Reputation: 33078

Try:

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

The problem with the code you wrote is that itemList.getClass() returns the class LinkedList. So the Array.newInstance() method is creating a LinkedList[], which you are then trying to typecast to an AuctionItem[]. Since these two types are incompatible for assignment, it throws a ClassCastException.

Upvotes: 6

Related Questions