来自Hashmap的java打印特定记录
我有一个Hashmap,我正在努力学习如何打印单个键和值。我可以打印所有这些,但想知道如何只打印其中一个谢谢
import java.util.HashMap;
public class Coordinate {
static class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
public String toString()
{
return x + ";" + y;
}
}
public static void main(String args[]) {
HashMap<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
map.put(new Coords(68, 78), "Amn");
map.put(new Coords(675, 89), "Ann");
System.out.println(map.size());
System.out.println(map.toString());
}
}
就目前来看
3
{65;72=Dan, 68;78=Amn, 675;89=Ann}
但我希望它只是展示
65;72=Dan
谢谢你的关注
# 1 楼答案
我想你一定要让它看起来更系统(关键是独一无二的):
然后,对于特定的值,您必须执行
System.out.println(map.get("Dan").toString());
,它将返回坐标更新:根据您的代码,它将是:
System.out.println(new Coords(x, y) + "=" + map.get(new Coords(x, y)));
# 2 楼答案
映射有一个名为get()的方法,可以接受一个键。对于给定坐标,将调用equals和hashcode方法来查找匹配值。使用这种方法
PS:equals方法总是假设要比较的对象是Coords,但事实可能并非如此
# 3 楼答案
只需从
HashMap
派生并重写其toString
方法