3

我有一个将对象作为哈希图值的代码。我想使用迭代器类从哈希图中读取 lat 和 lng。但我不知道该怎么做。这是我的代码。

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 值。请帮助

4

6 回答 6

5

你应该在这里使用泛型。将地图声明为

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
于 2013-01-01T13:53:55.633 回答
4

为什么不直接铸造价值?

Location locobj = (Location)me.getValue();
locobj.getLat();
locobj.getLng();
于 2013-01-01T13:40:28.907 回答
1

更改您的代码以使用泛型。

代替

Location locobj = new Location();
Map<Location> loc = new HashMap<Location>(); // code to interfaces, and use Generics

Location locobj = new Location();
HashMap<String,Location> loc = new HashMap<String,Location>();

并且您的条目为

Map.Entry<String,Location> me = (Map.Entry)i.next();

然后你就不必施放任何东西

于 2013-01-01T13:58:07.553 回答
0

getValue()返回您对 Object 的引用,但实际上 object 是 Location。因此,您需要执行强制转换,请参阅@DataNucleus 的答案,但您甚至可以这样做:

System.out.println(me.getKey()+"value>>"+((Location)me.getValue()).getLng()); 
于 2013-01-01T13:50:19.590 回答
0

您正在使用 getKey() 或 getValue() 检索对象。您现在需要调用 getter 方法来打印适当的值。

于 2013-01-01T13:51:53.187 回答
0

可以使用以下内容:

for (Entry entry : map.entrySet()) {
    String key = entry.getKey();
    Object values = (Object) entry.getValue();
    System.out.println("Key = " + key);
    System.out.println("Values = " + values + "n");
}
于 2014-12-01T07:39:11.267 回答