Java にキーと値のペアを入力し、 メソッドを使用してHashMap
に変換しました。String
toString()
String
この表現をオブジェクトに戻しHashMap
、対応するキーで値を取得することは可能ですか?
ありがとう
ベストアンサー1
toString() にオブジェクトの復元に必要なすべてのデータが含まれている場合に機能します。たとえば、文字列のマップ (文字列がキーと値として使用される場合) では機能します。
// create map
Map<String, String> map = new HashMap<String, String>();
// populate the map
// create string representation
String str = map.toString();
// use properties to restore the map
Properties props = new Properties();
props.load(new StringReader(str.substring(1, str.length() - 1).replace(", ", "\n")));
Map<String, String> map2 = new HashMap<String, String>();
for (Map.Entry<Object, Object> e : props.entrySet()) {
map2.put((String)e.getKey(), (String)e.getValue());
}
これは機能しますが、なぜこれが必要なのか本当に理解できません。