serialization - Need help to understand deserialization with ArrayList in Java -


i want write arraylist file , read again. list going hold integer objects. serialization seems working fine i'm having trouble deserilaizing. more can'get casting right.

the serialization:

objectoutputstream ou =     new objectoutputstream(new fileoutputstream(new file("load.dat")));  arraylist<integer> oulist = new arraylist<>(); ou.writeobject(oulist); ou.close(); 

the derserilazation:

objectinputstream in =     new objectinputstream(new fileinputstrean("load.dat")); arraylist<integer> inlist = (arraylist<integer>)(in.readobject(); in.close(); 

when compile unchecked , unsafe warning. recompiled xclint:unchecked , got following message:

warning: [unchecked] unchecked cast     arraylist<integer> inlist = (arraylist<integer>)(in.readobject());                                                     ^   required: arraylist<integer>   found:    object 

i find confusing: isn't casting supposed convert object arraylist? why require arraylist when that's i'm casting to? in advance help.

it tells compiler unable guarantee cast successful in runtime - may produce classcastexception.

usually able check type instanceof prevent warning, e.g.:

if (x instanceof arraylist) {     arraylist y = (arraylist) x; // no warning here  } 

unfortunately instanceof can't check generic parameters @ run-time, won't able perform operation safely. can suppress warning.

however if want assured of type of collection, can alter code in next way:

public class arraylistofintegers extends arraylist<integer> {}  ...  // writing: arraylistofintegers oulist = new arraylistofintegers(); ... // reading: arraylistofintegers inlist; object readdata = in.readobject(); if (readdata instanceof arraylistofintegers) {     inlist = (arraylistofintegers) readdata; } else {     throw new runtimeexception("..."); } 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -