我有一个带有 TreeMap 的可序列化对象。
Map<String, Dogs> dogsByNames = Maps.newTreeMap(); // guava style
到目前为止,一切都很好。现在可以忽略键的大小写:
Map<String, Dogs> dogsByNames = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
这不起作用,因为 String.CASE_INSENSITIVE_ORDER 不可序列化:
com.google.gwt.user.client.rpc.SerializationException:类型“java.lang.String$CaseInsensitiveComparator”未包含在可由此 SerializationPolicy 序列化的类型集中,或者无法加载其 Class 对象。出于安全考虑,此类型不会被序列化。: instance = java.lang.String$CaseInsensitiveComparator@f26f68
所以我创建了自己的:
private static abstract class MyComparator<T>
implements
Comparator<T>, // extends Ordering<T> do not work
IsSerializable { // Serializable do not work
}
public static final MyComparator<String> CASE_INSENSITIVE_ORDER = new MyComparator<String>() {
@Override
public int compare(final String left, final String right) {
if (null == left) {
return (null == right) ? 0 : -1;
} else if (null == right) {
return 1;
}
return left.compareToIgnoreCase(right);
}
};
但这仍然行不通。
怎么了?
解决方案:
protected static class MyOrdering // no-private!!!
extends
Ordering<String>
implements
IsSerializable {
@Override
public int compare(final String left, final String right) {
if (null == left) {
return (null == right) ? 0 : -1;
} else if (null == right) {
return 1;
}
return left.compareToIgnoreCase(right);
}
}
public static final Ordering<String> CASE_INSENSITIVE_ORDER = new MyOrdering();