如何返回 Vector java

发布于 2024-08-24 21:38:12 字数 388 浏览 4 评论 0原文

如何在 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;
    }

How do I return a vector in a java function. I want to unserialize a vector loaded from a file and return in a function but I get errors. This is what code I currently have.

    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;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

走过海棠暮 2024-08-31 21:38:12

您需要将从文件中读取的对象转换为向量:

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();
        }
     }

请注意,您无法检查它是否真的是国家向量(无法一一检查内容)。

You need to cast the object that you read from the file to 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();
        }
     }

Note that you cannot check if it is really a Vector of Countries (short of checking the contents one by one).

微暖i 2024-08-31 21:38:12

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

This is a wild guess, but try return (Vector<Countries>) object;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文