1

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?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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()]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.