Jim Vercoelen Jim Vercoelen - 1 year ago 164
Java Question

Java cast ObjectInputStream result to ArrayList

Is there a way to cast an OutputStream into an ArrayList at once?

I'am testing things out here and what I've got for example:


// Some list
List<Edge> edges = = new ArrayList<>();
edges.add(new Edge...)
edges.add(new Edge...)

OutputStream outStream = socket.getOutputStream();
ObjectOutputStream out = new ObjectOutputStream(outStream);


InputStream inStream = socket.getInputStream();
ObjectInputStream in = new ObjectInputStream(inStream);
Object inObject = in.readObject();
if (inObject.getClass() == ArrayList.class) {
System.err.println("IS LIST");
List<Edge> edges = (List<Edge>) in.readObject();


Jun 01, 2016 6:15:05 PM client.Client main
SEVERE: null
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2608)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at client.Client.main(Client.java:86)

Answer Source

EOFException is an "End Of File" exception. It means you attempted to read data when there is no more data to be read (already at the end of the file).

This occurs because you're reading 2 objects, but you are sending only 1. Instead of calling in.readObject() a 2nd time, simply cast the object you've already read:

list = (List<Edge>) inObject;