简体   繁体   English

将两个值与Java HashMap中的单个键相关联

[英]Associating two values to a single key in a java HashMap

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. 我试图将不同数据类型的两个值(一个长,另一个为字符串)关联到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. 我环顾四周,针对类似问题的建议包括使用Apache Collections Framework中的MultiValuedMap或Guava中的MultiMap。 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: 在插入HashMap时,请执行以下操作:

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! 谢谢!

Nothing wrong with your approach. 您的方法没有错。 As Java lacks a tuple class, you can define your own generically (instead of your class X ): 由于Java缺少元组类,因此可以通用地定义自己的类(而不是类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 另请参阅在Java中使用成对或2元组

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);

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. 您可以将任何对象存储为Map的值,在这种情况下,您只需使用自己的类即可包装两个单独的值。

As long as you don't use your custom class as the key, you're already done. 只要您不使用自定义类作为键,就已经完成了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM