Primitive alternative to Guava Table

1.4k views Asked by At

Is there an alternative to Guava Tables that uses primitives, instead of generic types, as the keys?

I would like to use primitives to avoid the auto-boxing caused by using Java Numbers and the additional entry objects created by Java Maps.

I've rolled my own basic LongLongObjectTable using Trove TLongObjectMap, but would prefer to use a standard library if one is available.

private static class LongLongObjectTable<T> {
    private final TLongObjectMap<TLongObjectMap<T>> backingMap = new TLongObjectHashMap<>();

    T get(final long rowKey, final long columnKey) {
        final TLongObjectMap<T> map = this.backingMap.get(rowKey);
        if (map == null) {
            return null;
        }
        return map.get(columnKey);
    }

    void put(final long rowKey, final long columnKey, final T value) {
        TLongObjectMap<T> map = this.backingMap.get(rowKey);
        if (map == null) {
            map = new TLongObjectHashMap<>();
            this.backingMap.put(rowKey, map);
        }
        map.put(columnKey, value);
    }

    Collection<T> values() {
        final List<T> values = new ArrayList<T>();
        for (final TLongObjectMap<T> map : this.backingMap.valueCollection()) {
            values.addAll(map.valueCollection());
        }
        return values;
    }
}
1

There are 1 answers

0
Daniel Langdon On

Not really. The problem is that such implementations are imminently not generic (by definition) and would need to be defined one by one. This means significant repetition and potentially a lot of possible collection permutations.

That said, other languages do allow this by making the compiler generate code for instances of a collection with type T rather than use type erasure, but that is not the direction java went.

The fact that you can use auto-boxed variants like Long or Integer on existing collection is good enough for the vast majority of cases, as the overhead is relatively low. Also, the designers of the standard library probably prefer to keep it slim rather than pollute it with additional custom variants.