Martyn Martyn - 1 year ago 77
Java Question

Cannot cast from ArrayList<Object> to ArrayList<MyObject>

I'm trying to create a generic loadFile method that can read a serialized object from a file. However the object type may vary depending on the file to load. I obviously misunderstood how casting works but can't really find what I ought to be doing here.

Below is my FileAdapter class:

public class FileAdapter {

public ArrayList<Transaction> loadTransactions() {

return (ArrayList<Transaction>) loadFile(new File("data/transactions.ser"));

public ArrayList<Fund> loadFunds() {

return (ArrayList<Fund>) loadFile(new File("data/funds.ser"));

private ArrayList<Object> loadFile(File file) {

ArrayList<Object> obj = new ArrayList<>();

FileInputStream fis = new FileInputStream(file);
in = new ObjectInputStream(fis);
obj = (ArrayList<Object>) in.readObject();

return obj;

As can be seen, I have two methods that load objects of different types from files but I want to share the code that actually loads the file. Is what I'm trying to do feasible but just wrongly implemented or can this not work at all if the types vary?

Answer Source

It could be done by defining a bounded type parameter in the definition of your method loadFile, as next:

public ArrayList<Transaction> loadTransactions(){
    return loadFile(new File("data/transactions.ser"));

public ArrayList<Fund> loadFunds(){
    return loadFile(new File("data/funds.ser"));

private <T> ArrayList<T> loadFile(File file) {
    ArrayList<T> obj = new ArrayList<>();
    return (ArrayList<T>) in.readObject();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download