是否可以更改数组列表的对象类型,即从对象 ArrayList 更改为特定对象 ArrayList。我尝试过对每个使用 a 。或者,是否有一种方法可以更改文件处理方法,以便它可以根据读取的文件返回特定类型,而无需重复代码?
我的尝试:
ArrayList<Object> librarianList = FileHandling.getLibrarianRecords(fileName);
ArrayList<Librarian> libList = new ArrayList<>();
for (Object addType: librarianList) {
libList.add(addType);
}
获取LibrarianRecords代码
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.
}
最佳答案
从这样的文件中读取对象并不是一个好主意。也就是说,您真正需要做的就是转换 oIS.readObject()
的结果。到ArrayList<Librarian>
而不是将其携带到 ArrayList<Object>
(就像你现在所做的那样)然后修改 getLibrarianRecords
的返回类型。哦,当然还有局部变量 fromFile
的类型.
public static ArrayList<Librarian> getLibrarianRecords(String filename){
ArrayList<Librarian> fromFile = new ArrayList<>(); //Array of
// existing librarians
try{
FileInputStream fIS =
new FileInputStream(SYSTEM_PATH + filename);
ObjectInputStream oIS = new ObjectInputStream(fIS);
fromFile = (ArrayList<Librarian>)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.
}
这样就不需要循环列表来实际逐个元素地进行类型转换。
关于java - 将 ArrayList 从对象更改为更具体的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53437868/