开发者

java.lang.classcastExcption

I have an array list of objects in my application.

private static ArrayList<Player> userList=new ArrayList<Player>();

In my application, I am converting this list to byte array and then sending it to other clients. At client When I am trying to cast it back to the ArrayList, its giving me casting err开发者_开发技巧or. I am doing this in client side after receiving this list as byte array:

ArrayList<Player> pl = (ArrayList<Player>) toObject(receivedByteArray); 

where toObject is my function to convert the byte array to object;

Any Suggestions please !!!

Thanks.

java.lang.ClassCastException: Player cannot be cast to java.util.ArrayList
        at Client.attemptLogin(Client.java:242)
        at Client.main(Client.java:64)


You should use Arrays.asList () instead:

List<Player> pl = Arrays.asList (toObject(receivedByteArray));

UPD: I'm not sure if it's only a naming issue: can you show the code, where you send/receive players? Does receivedByteArray contain Players or it really contains bytes? If second then there is no straightforward solution. Can you show a stacktrace?


I bet that you're talking about serialization, since that's the standard way to transfer Java objects as byte streams over some interfaces. I also assume that your Player class already implements java.io.Serializable, else you would have faced a NotSerializableException.

If you get a ClassCastException on one of the sides, then it means that the class file representing the Player class is not of exactly the same version. To fix this, you need either to ensure that the both sides are using exactly the same class file, or to add a private static final long SerialVersionUID with the same value to the class on the both sides.

Update as per the actual exception:

java.lang.ClassCastException: Player cannot be cast to java.util.ArrayList

It means that you're basically trying to do the following:

ArrayList<?> list = (ArrayList<?>) object;

where object is actually a Player. To fix this, you need to ensure that object is actually an ArrayList<?>, or you need to cast to Player instead.


byte[] can not be casted to/from ArrayList. If you need to represent your collection as a byte sequence, you probably need to serialize it. Use ObjectOutputStream and ObjectInputStream.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜