deserialise file, then store content in ArrayList<String>. (java)

55 views Asked by At

Assume serialise.bin is a file that is full of words and was an ArrayList when it was serialised

public static ArrayList<String> deserialise(){
    ArrayList<String> words= new ArrayList<String>();
    File serial = new File("serialise.bin");
    try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(serial))){ 
        System.out.println(in.readObject());   //prints out the content
    //I want to store the content in to an ArrayList<String>
    }catch(Exception e){
        e.getMessage();
    }
return words;
}

I want to be able to deserialise the "serialise.bin" file and store the content in an ArrayList

1

There are 1 answers

4
thatguy On BEST ANSWER

Cast it to ArrayList<String>, as in.readObject() does return an Object, and assign it to words:

@SuppressWarnings("unchecked")
public static ArrayList<String> deserialise() {

    // Do not create a new ArrayList, you get
    // it from "readObject()", otherwise you just
    // overwrite it.
    ArrayList<String> words = null;
    File serial = new File("serialise.bin");

    try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(serial))) { 
        // Cast from "Object" to "ArrayList<String>", mandatory
        words = (ArrayList<String>) in.readObject();
    } catch(Exception e) {
        e.printStackTrace();
    }

    return words;
}

The annotation @SuppressWarnings("unchecked") can be added to suppress a type-safety warning. It occurs, because you have to cast an Object to a generic type. With Java's type erasure there is no way of knowing for the compiler, if the cast is type-safe at runtime. Here is another post on this. Moreover e.getMessage(); does nothing, print it or use e.printStackTrace(); instead.