ArrayList<HashMap<String, String>> grpList2 的转化成Object类型
时间: 2023-10-14 11:10:17 浏览: 97
ArrayList,HashMap
ArrayList<HashMap<String, String>> grpList2 可以通过序列化(Serialization)来转换成 Object 类型。具体实现方法可以使用 Java 自带的序列化类 ObjectInputStream 和 ObjectOutputStream。示例代码如下:
```java
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
public class SerializeDemo {
public static void main(String[] args) {
ArrayList<HashMap<String, String>> grpList2 = new ArrayList<>();
HashMap<String, String> map1 = new HashMap<>();
map1.put("key1_1", "value1_1");
map1.put("key1_2", "value1_2");
HashMap<String, String> map2 = new HashMap<>();
map2.put("key2_1", "value2_1");
map2.put("key2_2", "value2_2");
grpList2.add(map1);
grpList2.add(map2);
// 将 ArrayList<HashMap<String, String>> 转换成 Object 类型
try {
FileOutputStream fileOut = new FileOutputStream("grpList2.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(grpList2);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in grpList2.ser");
} catch (IOException i) {
i.printStackTrace();
}
// 从 Object 类型转换回 ArrayList<HashMap<String, String>>
try {
FileInputStream fileIn = new FileInputStream("grpList2.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
ArrayList<HashMap<String, String>> grpList2FromSer = (ArrayList<HashMap<String, String>>) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized data:");
System.out.println(grpList2FromSer.get(0).get("key1_1"));
System.out.println(grpList2FromSer.get(0).get("key1_2"));
System.out.println(grpList2FromSer.get(1).get("key2_1"));
System.out.println(grpList2FromSer.get(1).get("key2_2"));
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("ArrayList<HashMap<String, String>> class not found");
c.printStackTrace();
return;
}
}
}
```
输出结果为:
```
Serialized data is saved in grpList2.ser
Deserialized data:
value1_1
value1_2
value2_1
value2_2
```
阅读全文