java - 如何将两种不同的列表类型序列化/反序列化为单个顺序文件
问题描述
我有三个不同的联系人类型列表,我需要将它们序列化到一个文件中,然后在需要时检索这些列表(反序列化)。我曾考虑过使用哈希图,但我不熟悉,我确定如何完整地检索列表。任何想法表示赞赏。
我不确定是否可以在哈希图中使用 Object 类型。这是我能够将所有三个列表添加到哈希图中的一种方式。如果这是最好的方法,我还需要知道从哈希图中检索这些列表的正确方法。
public class Controller()
{
// the list objects I need to serialize
List<FamilyContact> friendContacts = new ArrayList<FamilyContact>();
List<Contact> fdContacts = new ArrayList<>(friendContacts);
List<FamilyContact> familyContacts = new ArrayList<FamilyContact>();
List<Contact> fContacts = new ArrayList<>(familyContacts);
// methods to retrieve the lists and list items
}
//Serialization code
public class Serialization
{
public void serialize(HashMap<String, Object> lists, String fileName)
{
// serializes the hashmap passed from calling method
try (ObjectOutputStream output =
new ObjectOutputStream(new FileOutputStream(fileName)))
{
output.writeObject(lists);
output.close();
}
catch(IOException ex)
{
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public HashMap<String, Object> deserialize(String fileName)
{
try (ObjectInputStream input =
new ObjectInputStream(new FileInputStream(fileName)))
{
HashMap<String, Object> lists = (HashMap)input.readObject();
System.out.println(lists.size());
input.close();
return lists;
}
catch (IOException | ClassNotFoundException ex)
{
if(ex.getClass().getName() == "java.io.FileNotFoundException")
{
showErrorDialog("File Not Found", "Contacts.ser not found");
}
else
{
System.out.println(ex.getClass().getName());
System.out.println(ex.getMessage());
}
}
return null;
}
解决方案
当您反序列化一个对象时,它 [通常] 与您序列化它的类型相同。所以连载是一条红鲱鱼。
在这种情况下使用 aMap
通常是不必要的事情。特别是当你有不同的类型时,这将导致铸造。
因此,您可能需要一个 [不可变] 值类型,以通常 [过度冗长] 的方式编写。
推荐阅读
- c# - 如何使控件扩展通过控件绑定或与其他控件重叠?
- mysql - 触发值,调用表列并与文本连接
- excel - VBA - 在 Sheets.Range 中使用平均函数
- android - 未找到处理 Intent { act=android.app.action.ADD_DEVICE_ADMIN (has extras) } 的 Activity
- java - Java - 我可以使用 JarURLConnection 来执行 jar 类吗?
- python - 分类的正确编码(标签)
- wordpress - get_terms(get_the_ID) 显示 WP_Error
- javascript - 如何在驼峰键名之间添加空格?
- python - 通过在 tensorflow 中运行会话来最小化开销
- html - 如何在 wordpress 上预加载字体?