我如何返回一个 Vector java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2423238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:04:38  来源:igfitidea点击:

How do I return a Vector java

javafunctionvector

提问by Hultner

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.

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

回答by Thilo

You need to cast the object that you read from the file to Vector:

您需要将从文件中读取的对象转换为 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).

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

回答by polygenelubricants

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

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