Search code examples
javaobjectarraylistfile-handlingobject-type

Change ArrayList from an Object to more specific type


Is it possible to change the object type of an array list i.e. from an Object ArrayList to a specific object ArrayList. I have tried using a for each. Alternatively is there a way to change the filehandling method such that it can return a specific type depending on which file it reads from without duplicating code?

My Attempt:

ArrayList<Object> librarianList = FileHandling.getLibrarianRecords(fileName);
ArrayList<Librarian> libList = new ArrayList<>();
for (Object addType: librarianList) {
libList.add(addType);
}

getLibrarianRecords code

public static ArrayList<Object> getLibrarianRecords(String filename){
                ArrayList<Object> fromFile = new ArrayList<>(); //Array of
                // existing librarians

                try{
                        FileInputStream fIS =
                                new FileInputStream(SYSTEM_PATH + filename);
                        ObjectInputStream oIS = new ObjectInputStream(fIS);
                        fromFile = (ArrayList<Object>)oIS.readObject();
                } catch (IOException ex){
                        System.out.println("Failed to read from file " + ex.getMessage());
                        ex.printStackTrace(); //Catches an IO exception.
                } catch (ClassNotFoundException ex){
                        System.out.println("Error class not found" + ex.getMessage());
                        ex.printStackTrace(); //Catches a class not found
                        // exception.
                }

                return fromFile; //Returns the array list.
        }

Solution

  • Thanks to @user3170251 for suggesting casting

    ArrayList<Object> librarianList = FileHandling.getLibrarianRecords(fileName);
    ArrayList<Librarian> libList = new ArrayList<>();
    for (Object addType: librarianList) {
    libList.add((Librarian) addType);
    }
    

    For changing the type this does work.