gpt4 book ai didi

java - 创建一个以元组为键的哈希表

转载 作者:行者123 更新时间:2023-12-02 01:22:30 27 4
gpt4 key购买 nike

正如标题所说,我想创建一个以整数元组为键的哈希表。到目前为止我所做的:

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



public class Class1{
public static void main(String[] args){
Tuple t= new Tuple (1,1);
HashMap<Tuple, Integer> seen = new HashMap<Tuple, Integer>();
seen.put(t,33);

System.out.println(seen.get(t));
}
}

我的问题是这样的:我只想通过知道元组 (1,1) 而实际上不知道对象 t 来获取值 33。类似 seen.get((1,1)) 的值,值为 33。

如何实现这一目标?

最佳答案

你会做

System.out.println(seen.get(new Tuple(1, 1));

关键概念是,由于您重写了 equals 和 hashCode,所以满足相等性和 hashCode 相等性的任何 元组对象都将用作键,而不仅仅是 t 对象。

编辑:

请注意,您的 Tuple 类还必须以正确的方式重写 public boolean equals(Object o) 方法,以使其中任何一个都能正常工作:

public class Tuple {
private int x;
private int y;

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 obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tuple other = (Tuple) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}

然后测试:

public static void main(String[] args) {
Tuple t = new Tuple(1, 1);
Map<Tuple, Integer> seen = new HashMap<Tuple, Integer>();
seen.put(t, 33);

System.out.println(seen.get(t));
System.out.println(seen.get(new Tuple(1, 1)));
}

关于java - 创建一个以元组为键的哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57445657/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com