2017-08-07 3 views
-1

Javaオブジェクトのシリアライズ:このタイプのハッシュテーブルを(Integer、Employee)のようにシリアライズしました。これを逆シリアル化するとき、出力をa HashMap。これは可能ですか?私はjava.lang.ClassCastExceptionがJavaオブジェクトのシリアライゼーション:Hashtableをシリアライズし、HashMapで逆シリアル化します。

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

はあなたの努力 – sForSujit

+0

を表示すぎ – sForSujit

+0

@sForSujitなぜ従業員&パーソンクラスを表示?彼らは答えを変えない。 – EJP

答えて

0

を取得するので、これは可能ですか?

はい。しかし、それをコード化した方法ではありません。あなたはあなた自身のHashMapを作成し、HashTableからそれをロードする必要があります:

HashMap<Integer,Employee> hm= new HashMap<>((HashTable<Integer, Employee>)ois.readObject()); 
関連する問題