Java对象序列化:序列化Hashtable,然后在HashMap中反序列化它

时间:2017-08-07 07:45:52

标签: java serialization hashmap deserialization hashtable

Java对象序列化:我将此类型的Hashtable序列化为(Integer,Employee),当我反序列化时,我想将输出放在HashMap中。这可能吗?因为我得到了java.lang.ClassCastException

public class Employee implements Serializable {
  private static final long serialVersionUID = -7260877684654746408L;
  private String name;
  private int age;

  Employee(String n, int a) {
    name=n;
    age=a;
  }

  public String toString() {
    return "Name: "+name+". "+"Age: "+age+".";
  }

}

    public class Test {

      public static void main(String[] args) {
        Hashtable<Integer, Employee> ht = new Hashtable<Integer, Employee>() {
          {
            put(1, new Employee("John", 37));
            put(2, new Employee("Julia", 36));
          }
        };

        //HashMap<Integer,Employee> hm = new HashMap<Integer,Employee>();


        try {
          FileOutputStream outSer = new FileOutputStream("outSer.ser");
          ObjectOutputStream os = new ObjectOutputStream(outSer);
          os.writeObject(ht);
          os.close();

          FileInputStream input = new FileInputStream("outSer.ser");
          ObjectInputStream ois = new ObjectInputStream(input);
          HashMap<Integer,Employee> hm= (HashMap<Integer, Employee>)ois.readObject();
          ois.close();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }

    }

1 个答案:

答案 0 :(得分:0)

  

这可能吗?

是。但不是你编码的方式。您必须创建自己的HashMap并从HashTable

加载它
HashMap<Integer,Employee> hm= new HashMap<>((HashTable<Integer, Employee>)ois.readObject());