Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive alternative to Guava Table

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;
    }
}
like image 896
Jake Walsh Avatar asked Aug 21 '13 20:08

Jake Walsh


People also ask

Is map a primitive type?

The keys and values of a map can be any reference type. We can't use primitive types because of a restriction around the way generics were designed. A HashMap allows one null key and multiple null values. It doesn't preserve the order of the elements and doesn't guarantee the order will remain the same over time.


1 Answers

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.

like image 64
Daniel Langdon Avatar answered Sep 21 '22 23:09

Daniel Langdon