gpt4 book ai didi

java - 从 Hashmap 打印特定记录

转载 作者:行者123 更新时间:2023-12-02 07:39:07 24 4
gpt4 key购买 nike

我有一个 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

感谢您的浏览

最佳答案

Map.get(K) 方法允许您检索所需键的值。所以你可以这样做:

Coords c = new Coords(65,72);
System.out.println(c + " -> " + map.get(c));

这适用于任何类型的 Map,包括 HashMap 和 TreeMap。您还可以使用 Map.keySet() 获取 map 中所有键的集合。

关于java - 从 Hashmap 打印特定记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11818148/

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