从guava集合中对HashBasedTable进行子类化

Gau*_*tam 2 java gwt guava

我有一个多级地图要求,我正在使用番石榴表.更准确地说是HashBasedTable.

由于我的代码需要对此数据集进行大量自定义处理,因此我希望实现一个派生类,例如EventActionRuleTable,它包含一个针对源的Event - Action对象的映射.

这样的事情

HashMap<Source , Map<Event, Action> ruleMap ; 
Run Code Online (Sandbox Code Playgroud)

我用一个替换上面的

Table<Source, Event , Action> ruleTable = HashBasedTable.create();
Run Code Online (Sandbox Code Playgroud)

但是为了保存我的所有自定义代码,我想将HashBasedTable子类化,并认为它根本不可能.

因此,我选择与代表一起去,即

public EventActionRule extends Table<Source, Event, Action>{

private HashBasedTable<Source, Event, Action> backup = null ;

public HashBasedTable<Source, Event, Action> getBackupTable() {

    if (backupTable == null) {
        backupTable = HashBasedTable.create() ;
    }

    return backupTable;
}  

@Override
public boolean isEmpty() {
    return getBackupTable().isEmpty();
}

/**
All other methods of Table interface overridden to delegate calls to backup instance
*/
  ....
}
Run Code Online (Sandbox Code Playgroud)
  1. 这种方法是否正确?如果不是,你能列出问题吗?任何替代方法?

  2. HashBasedTable Gwt序列化兼容吗?我问,因为HashBasedTable内部使用的两个备份映射都使用@GwtTransient注释进行了注释.

Xae*_*ess 6

广告1.您的方法是正确的,尽管您可以使用内置的Guava解决方案来使用委托 - 转发装饰器:

对于所有各种集合接口,Guava提供了Forwarding抽象类来简化使用装饰器模式.

在你的情况下,ForwardingTable等着你:

public static class EventActionRule extends ForwardingTable<Source, Event, Action> {

    private Table<Source, Event, Action> delegate = HashBasedTable.create();

    @Override
    protected Table<Source, Event, Action> delegate() {
        return delegate;
    }

    // just an example: isEmpty (and other methods) is ready to be overriden
    @Override
    public boolean isEmpty() {
        boolean isEmpty = delegate().isEmpty();
        System.out.println("Was map empty? " + isEmpty);
        return isEmpty;
    }
}
Run Code Online (Sandbox Code Playgroud)

广告.2.是的,HashBasedTable在GWT下是可序列化的.

  • 需要注意的是:除非你需要改变它的行为,否则你不必用`ForwardingTable`覆盖`isEmpty()`.`return delegate().isEmpty()`是默认情况下会执行的操作. (2认同)
  • @Gautam @Xaerxess:`HashBasedTable`标记为`@GwtCompatible(serializable = true)`,因此它是GWT可序列化的.至于为什么字段是GWT的瞬态,该类有一个自定义GWT序列化器:[`HashBasedTable_CustomFieldSerializer`](https://github.com/google/guava/blob/master/guava-gwt/src/com/google/通用/收集/ HashBasedTable_CustomFieldSerializer.java). (2认同)