【问题标题】:Java Object Serialization: serialize a Hashtable, then deserialize it in a HashMapJava对象序列化:序列化一个Hashtable,然后在HashMap中反序列化
【发布时间】:2017-08-07 07:45:51
【问题描述】:

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

    }

【问题讨论】:

  • 展示你的努力
  • 也显示 Employee & Person 类
  • @sForSujit 为什么?他们不会改变答案。

标签: java serialization hashmap deserialization hashtable


【解决方案1】:

这可能吗?

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2010-10-19
    • 1970-01-01
    • 2011-08-26
    • 2017-08-02
    • 2011-05-10
    • 1970-01-01
    • 2016-08-20
    相关资源
    最近更新 更多