Reputation: 1993
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
Upvotes: 3
Views: 20095
Reputation: 397
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");
}
Upvotes: 0
Reputation: 3006
You are retrieving an Object with getKey() or getValue(). You need to now call the getter methods to print the appropriate values.
Upvotes: 0
Reputation: 1239
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
Upvotes: 1
Reputation: 7375
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
Upvotes: 5
Reputation: 9579
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());
Upvotes: 0
Reputation: 15577
Why not just cast the value?
Location locobj = (Location)me.getValue();
locobj.getLat();
locobj.getLng();
Upvotes: 4