简体   繁体   中英

how to get hashmap object value

i have a code which put object as hashmap value. I want to read lat and lng from the hashmap using iterator class. But i dont know how to do this.here is my code.

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()); 
      }

class location is like this

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;
    }

}

how do i read locobj lat and lng value from getValue() method.please help

You should make use of generics here. Declare Map as

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

That way, you can avoid typecasting (RTTI should be avoided - one of the design principles)

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

Why not just cast the value?

Location locobj = (Location)me.getValue();
locobj.getLat();
locobj.getLng();

Change your code to use Generics.

Instead of

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

do

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

and your entry as

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

Then you won't have to cast anything

getValue() returns you reference to Object, but in fact object is Location. So you need to perform casting, see answer from @DataNucleus, but you can do even like this:

System.out.println(me.getKey()+"value>>"+((Location)me.getValue()).getLng()); 

You are retrieving an Object with getKey() or getValue(). You need to now call the getter methods to print the appropriate values.

The following can be used:

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM