How do you serialize a guava collection?

故事扮演 提交于 2019-12-12 14:39:57

问题


I must be missing something obvious but I can't manage to serialize a TreeBasedTable. It is marked as @GwtCompatible(serializable = true), so my understanding is that I need to use the guava-gwt library to (de-)serialize it.

But I can't find do that. A contrived code example would be extremely appreciated.

For information, my pom contains guava and guava-gwt, both version 14.0.

EDIT

So thanks to the answer, I now understand that TreeBasedTable is serializable. So I have removed all the gwt references and got it to work. However, this code still fails (which is the code that made me think that TreeBasedTable was not serializable) - so I guess the problem is with the custom Comparators...

public static void main(String[] args) throws Exception {
    //with the following table it works
    //Table<Integer, String, Object> table = TreeBasedTable.create();

    //but with this one, it fails
    Table<Integer, String, Object> table = TreeBasedTable.create(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o1.compareTo(o2);
        }
    }, String.CASE_INSENSITIVE_ORDER);

    table.put(1, "s", 123);

    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(Paths.get("c:/temp/test").
            toFile()));) {
        oos.writeObject(table);
    }

    Table<Integer, String, Object> saved = null;

    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Paths.get("c:/temp/test").
            toFile()));) {
        saved = (Table<Integer, String, Object>) ois.readObject();
    }

    System.out.println(table.equals(saved));
    Files.delete(Paths.get("C:/temp/test"));
}

回答1:


If you are talking about plain Java serialization, yes: TreeBasedTable is Serializable.

TreeBasedTable extends StandardRowSortedTable which extends StandardTable which implements Serializable.

BTW: a simple check would have helped you:

Serializable foo = TreeBasedTable.create();

Since the compiler doesn't complain about this line, you know that TreeBasedTable implements Serializable.


Update:

String.CASE_INSENSITIVE_ORDER implements Serializable, so all you need to do is to refactor your anonymous Integer comparator into an inner class that implements Serializable. Or: better yet, use Ordering.natural() instead, which is Serializable already.



来源:https://stackoverflow.com/questions/15351587/how-do-you-serialize-a-guava-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!