如何返回Vector java

问题描述 投票:0回答:2

如何在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;
    }
java function vector
2个回答
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
投票

这是一个疯狂的猜测,但尝试return (Vector<Countries>) object;

© www.soinside.com 2019 - 2024. All rights reserved.