开发者

Java Dictionary value of type tuple

开发者 https://www.devze.com 2023-01-31 06:04 出处:网络
I want a Dictionary (HashTable, Map, ...) that has one key and several values. I.e. I want something like

I want a Dictionary (HashTable, Map, ...) that has one key and several values.

I.e. I want something like

HashTable&开发者_如何学Pythonlt;Key, [value1, value2]>

How do I get this?


The easiest way I think:

Map<Key, List<Value>>

If you would rather just have a tuple (pair, 3, or ...) you can create a Pair class.

class Pair<E,F, ...> {

    public E one;
    public F two;
    ...

}

And then use a Map like so:

Map<Key, Pair<Value, Value>>


How about HashTable<Key, List<Value>>?


Just store an array as the value with defined length?


Make a new (non-public) class for your values or use multiple maps (propably slower).


Google's Guava provides a multimap that does this. Javadoc


There's no such thing as tuples in Java Language, so you can use some of the proposals:

  • store an array
  • store a List, Set
  • store a custom object holding the two values

You also can make a fairly general object: Pair.

public Pair<A,B> {
  public Pair(A a, B b) {
   this.a = a;
   this.b = b;
  }
  public A a() { return a; }
  public B b() { return b; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消