gpt4 book ai didi

java - 如何获取hashmap对象值

转载 作者:行者123 更新时间:2023-12-01 16:40:09 24 4
gpt4 key购买 nike

我有一个将对象作为 HashMap 值的代码。我想使用迭代器类从 HashMap 中读取纬度和经度。但我不知道该怎么做。这是我的代码。

Location locobj = new Location();
HashMap loc = new HashMap();

while(rs.next()){
locobj.setLat(lat);
locobj.setLng(lon);
loc.put(location, locobj);

}

Set set = loc.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey()+"value>>"+me.getValue());
}

上课地点是这样的

public class Location {

private String lat;
private String lng;
private String name;

public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

我如何从 getValue() 方法读取 locobj lat 和 lng 值。请帮助

最佳答案

您应该在这里使用泛型。将 map 声明为

Map<String, Location> locationMap = new HashMap<>() // assuming your key is of string type

这样,您就可以避免类型转换(应该避免 RTTI - 设计原则之一)

Location locobj = me.getValue()
locobj.getLat() // will give you latitude
locobj.getLng() // will give you longitude

关于java - 如何获取hashmap对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14110924/

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