list中存在的map数据如何获取
代码如下:
package Map04;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Map04 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
Person p1=new Person(001, "test1", "13585114154");
Person p2=new Person(002, "test2", "13585114154");
list.add(p1.toMap());
list.add(p2.toMap());
//遍历list,里面是HashMap
for(int i=0;i<list.size();i++)
{
Map<String, Object> map=new HashMap<String, Object>();
Iterator<String> it=map.keySet().iterator();
while(it.hasNext())
{
//得到key
String key=it.next();
Person p=(Person) map.get(key);
System.out.print(p.getName());
}
}
}
}
class Person{
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
private String name;
private String phone;
public Person(int id,String name,String phone)
{
this.id=id;
this.name=name;
this.phone=phone;
}
public Map<String, Object> toMap()
{
Map<String, Object> map=new HashMap<String, Object>();
map.put(String.valueOf(id), new Person(id, name, phone));
return map;
}
}
//运行结果为空,控制台也没有数据打印出来
String key=it.next();
Person p=(Person) map.get(key);
System.out.print(p.getName());