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;
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With