首页 > 解决方案 > 如何将两种不同的列表类型序列化/反序列化为单个顺序文件

问题描述

我有三个不同的联系人类型列表,我需要将它们序列化到一个文件中,然后在需要时检索这些列表(反序列化)。我曾考虑过使用哈希图,但我不熟悉,我确定如何完整地检索列表。任何想法表示赞赏。

我不确定是否可以在哈希图中使用 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;
    }

标签: javalistarraylistabstract-classsubclass

解决方案


当您反序列化一个对象时,它 [通常] 与您序列化它的类型相同。所以连载是一条红鲱鱼。

在这种情况下使用 aMap通常是不必要的事情。特别是当你有不同的类型时,这将导致铸造。

因此,您可能需要一个 [不可变] 值类型,以通常 [过度冗长] 的方式编写。


推荐阅读