java - 如何将两种不同的列表类型序列化/反序列化为单个顺序文件

标签 java list arraylist abstract-class subclass

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

我不确定是否可以在 HashMap 中使用对象类型。这是我能够将所有三个列表添加到 HashMap 的一种方法。 另外,如果这是最好的方法,我还需要知道从 HashMap 中检索这些列表的正确方法。

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;
    }

最佳答案

当您反序列化一个对象时,它[通常]会以与您序列化它相同的类型出现。所以序列化是一个转移注意力的事情。

在这种情况下使用 map 通常是不必要的。特别是当你有不同的类型时,这将导致强制转换。

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

关于java - 如何将两种不同的列表类型序列化/反序列化为单个顺序文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55926896/

相关文章:

java - Spring servlet配置文件抛出异常

java - 能够使用 jackson 循环从 json 响应返回的每个用户

java - 如何将ArrayList存储在文件中?

java - 查找数组列表中的重复元素

java - [学习EJB] : annotation type is not applicable to this kind of declaration?

java - 如何在Java中创建嵌套菜单?

java - 使用 SimpleCursorAdapter 保留 highlite 列表项

python - 简化 Python 中的列表过滤器

python - 为什么元组比 Python 中的列表快?

ios - iPhone中类似于Android ArrayList的任何内容