从番石榴集合中继承 HashBasedTable

Subclassing HashBasedTable from guava collection

我有一个多级地图需求,我正在使用 Guava Table。更准确地说是 HashBasedTable。

由于我的代码需要对此数据集进行大量自定义处理,因此我想实现一个派生的 class,例如EventActionRuleTable 持有一个 Event - Action 对象对源的映射。

像这样

HashMap<Source , Map<Event, Action> ruleMap ; 

我将上面的替换为

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

但是为了保存我所有的自定义代码,我想 subclass 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
*/
  ....
}
  1. 这种方法正确吗?如果不是,你能列出问题吗?任何替代方法?

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

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

For all the various collection interfaces, Guava provides Forwarding abstract classes to simplify using the decorator pattern.

在你的情况下,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;
    }
}

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