2

I am trying to associate two values of different datatypes [one long and the other a string] to a single key in a Java HashMap. I have looked around and suggestions to similar problems include, using the MultiValuedMap from the Apache Collections Framework or using the MultiMap from Guava. However I think these may be overkill plus I would not like to add extra binaries to my system.

Is there anything wrong with defining a class such as:

class X {
    long value1;
    String value2;
    X(long v, String w) { this.value1 = v; this.value2 = w;}
}

While inserting into the HashMap do this:

X obj = new X(1000, "abc");
map.add("key", obj)

Are there any glaring drawbacks with this approach? I am looking for a solution that scales well in lookup.

Thanks!

z00lander
  • 65
  • 4

2 Answers2

2

Nothing wrong with your approach. As Java lacks a tuple class, you can define your own generically (instead of your class X):

public class Tuple<X, Y> { 
  public final X x; 
  public final Y y; 
  public Tuple(X x, Y y) { 
    this.x = x; 
    this.y = y; 
  } 
} 

see also Using Pairs or 2-tuples in Java

The usage would then be as follows:

    Map<String,Tuple<Long,String>> map = new HashMap<>();
    Tuple<Long,String> obj = new Tuple<>(1000L, "abc");
    map.put("key", obj);
Raphael Roth
  • 26,751
  • 15
  • 88
  • 145
0

It's totally fine. You can store any object as the value in a Map, in this case you simply use your own class to wrap two individual values.

As long as you don't use your custom class as the key, you're already done.

f1sh
  • 11,489
  • 3
  • 25
  • 51