如何在java函数中返回向量。我想反序列化从文件加载的向量并返回函数但我得到错误。这就是我目前的代码。
private static Vector<Countries> loadOB(String sFname) throws ClassNotFoundException, IOException {
ObjectInputStream oStream = new ObjectInputStream(new FileInputStream(sFname));
Object object = oStream.readObject();
oStream.close();
return object;
}
答案 0 :(得分:5)
您需要将从文件中读取的对象强制转换为Vector:
private static Vector<Countries> loadOB(String sFname) throws ClassNotFoundException, IOException {
ObjectInputStream oStream = new ObjectInputStream(new FileInputStream(sFname));
try{
Object object = oStream.readObject();
if (object instanceof Vector)
return (Vector<Countries>) object;
throw new IllegalArgumentException("not a Vector in "+sFname);
}finally{
oStream.close();
}
}
请注意,您无法检查它是否真的是国家的向量(除了逐个检查内容)。
答案 1 :(得分:1)
这是一个疯狂的猜测,但请尝试return (Vector<Countries>) object;