问题
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