【发布时间】:2018-11-22 20:54:32
【问题描述】:
是否可以更改数组列表的对象类型,即从对象 ArrayList 到特定对象 ArrayList。我试过为每个使用一个。或者,有没有一种方法可以更改文件处理方法,使其可以根据读取的文件返回特定类型,而无需重复代码?
我的尝试:
ArrayList<Object> librarianList = FileHandling.getLibrarianRecords(fileName);
ArrayList<Librarian> libList = new ArrayList<>();
for (Object addType: librarianList) {
libList.add(addType);
}
getLibrarianRecords 代码
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.
}
【问题讨论】:
-
您的文件是什么样的?
Librarian类是什么样的? -
这段代码有效吗?可以显示输入输出吗?
-
为什么不首先从您的 read 方法中返回一个图书馆员列表?
-
代码不起作用,因为它不是正确的对象类型。我得到一个无法转换的错误。当我指定对象类型时,文件处理方法有效。 @死侍
-
我有大约 8 个类似的方法,其中只有数组列表的对象类型发生了变化。我试图在不重新输入的情况下回收代码。 @大牛
标签: java object arraylist file-handling object-type