Reputation: 381
i want to do something like this, anyone done something similar? I have one solution map that has two keys, i am using it for geolocation, but i would like to make it with n number of keys instead.
import java.util.Collection;
import java.util.Set;
public interface NKeyMap<K..., V> {
public void clear();
public boolean containsKey(K...);
public boolean containsValue(V value);
public V get(K...);
public boolean isEmpty();
public V put(K..., V value);
public V removeK..., V value);
public int size();
public Collection<V> values();
public Set<K...> keys();
}
Upvotes: 3
Views: 2736
Reputation: 6170
You can not do var-arg generic but you can do something like below
import java.util.Collection;
import java.util.Set;
public interface NKeyMap<K, V> {
public void clear();
public boolean containsKey(K... k );
public boolean containsValue(V value);
public V get(K... k);
public boolean isEmpty();
public V put(V value, K...k);
public V remove(V value, K... k);
public int size();
public Collection<V> values();
public Set<K> keys();
}
Upvotes: 2
Reputation: 31972
Take a look at this post The person tries to simulate this by chaining pair
He does this
Pair<String, Integer> pair = Pairs.pair("hello", 5);
Pair<Double, Pair<String, Integer>> withDouble = Pairs.pair(3.0, pair);
And proposes the below to make it cleaner
public class Pair<T, U> { ...
public <V> Pair<V, Pair<T, U>> prepend(V v) {
return pair(v, this); } }
So that it becomes
Pair<Double, Pair<String, Integer>> pair = Pairs.pair("hello", 5).prepend(3.0);
Note: you might need to write Pair
.
Note: Seems he actually endorses javatuples at the end..
More relevant:
After reading your comment, this more obvious solution presents itself. Multidimensional maps, much like multimensional arrays
Map<XKey, Map<YKey, Value> >
Upvotes: 2
Reputation: 11474
If you need variable-length keys, you can use javatuples or something similar, which wrap an arbitrary number and arbitrary types of arguments (they provide tuples until a length of 10):
Map<Triplet<Double,Float,Integer>, Object> mapWithCombinedKeys = ...
Upvotes: 1