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 error. 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)
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
Playerclass already implementsjava.io.Serializable, else you would have faced aNotSerializableException.If you get a
ClassCastExceptionon one of the sides, then it means that the class file representing thePlayerclass 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 aprivate static final long SerialVersionUIDwith the same value to the class on the both sides.Update as per the actual exception:
It means that you’re basically trying to do the following:
where
objectis actually aPlayer. To fix this, you need to ensure thatobjectis actually anArrayList<?>, or you need to cast toPlayerinstead.