Hultner
Hultner

Reputation: 3780

How do I return a Vector java

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

Upvotes: 0

Views: 17442

Answers (2)

Thilo
Thilo

Reputation: 262534

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).

Upvotes: 5

polygenelubricants
polygenelubricants

Reputation: 383756

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

Upvotes: 1

Related Questions