简体   繁体   English

使用元组作为键的哈希图

[英]Hashmap using tuple as key

What I would like to do is create a hashmap that uses a tuple as a key. 我想做的是创建一个使用元组作为键的哈希图。 What I have done so far: 到目前为止,我所做的是:

HashMap<String, Integer> seen = new HashMap<String, Integer>();

and for the key I use (X+"#"+Y) with X, Y being integers. 对于键,我使用(X+"#"+Y)其中X为Y,Y为整数。 So, when I have two integers I just need to search for this string. 因此,当我有两个整数时,我只需要搜索此字符串。 However, for very large and many X and Y creating large strings instead of a tuple of integers eats up a lot of memory. 但是,对于非常大的X和Y,创建大型字符串而不是整数元组会占用大量内存。 How could this be done using (X, Y) and not (X+"#"+Y) ? 如何使用(X, Y)而不是(X+"#"+Y)

You could create your own class called Tuple that overrides Java's hashCode() function (I assume Java's default implementation won't work for this so you'll have to make your own), which you could then use as the key to your Hashmap :) 您可以创建自己的名为Tuple的类,该类重写Java的hashCode()函数(我假设Java的默认实现对此无效,因此您必须自己创建),然后可以将其用作Hashmap的键: )

EDIT: As many people have already mentioned, I forgot to override equals() as well. 编辑:正如很多人已经提到的,我也忘记了覆盖equals()。 Here is the implementation including the equals() function. 这是包含equals()函数的实现。

Something like this should do: 这样的事情应该做:

class Tuple {
  public Tuple(int x, int y) {
    this.x = x;
    this.y = y;
  }

  @Override
  public int hashCode() {
    int hash = 17;
    hash = 31 * hash + this.x;
    hash = 31 * hash + this.y;
    return hash;
  }

  @Override
  public boolean equals(Object other) {
    if (this == other) return true;
    if (other == null) return false;
    if (this.getClass() != other.getClass()) return false;
    Tuple that = (Tuple) other;
    return (this.x == that.x) && (this.y == that.y);
  }

  private int x;
  private int y;
}

Though as previously mentioned, you could just use Java's java.awt.Point :) 尽管如前所述,您可以只使用Java的java.awt.Point :)

You could write your own pair class which is probably the preferred way to go about this, but javax.util also has its own Pair class but the implementation is quite sparse so i usually avoid it. 您可以编写自己的pair类,这可能是解决此问题的首选方法,但是javax.util也有自己的Pair类,但是实现非常稀疏,因此我通常避免使用它。

If you do chose to write your own pair class, you must override Object's hashcode and equals methods 如果确实选择编写自己的配对类,则必须重写Object的哈希码和equals方法

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

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