2014-01-16 35 views
-3
Person{  
private String name;  
private Long id;  
setter & getter  
} 

HashMap hashKey = new HashMap();HashMap和POJO的

HashMap如何把 POJO属性,以及如何让他们

,并可以在任何给我的帮助

+1

你的努力在哪里? –

+0

您正在寻找“The Reflection API”......可能。 – mschonaker

+0

@mschonaker我真的怀疑你的意见。 –

回答

2

这是很容易

Person person=new Person(); // create instance 
    person.setName("name"); //set values 
    person.setId("id"); 

    HashMap<String,Person> hashKey = new HashMap<String,Person>(); 
    hashKey.put("key",person); //add person instance to Map with key 

Map中的值为Person类型,只有你必须确保你正在使用相关密钥将Map个人实例。

当您想从Map中检索数据时,可以采用以下方法。现在

Person person=hashKey.get("key") // retuning a person 

你可以使用getter方法person数据包含。

String name=person.getName(); 
String id=person.getId();  
+0

您不能在左侧使用钻石。你可以在JAVA SE 7的版权中使用它 – Keerthivasan

1

HashMap是通过类型参数化的泛型类。可以很好地使类型参数使用您的POJO类的用钥匙作为字符串类型或任何非基本类型

//declaration and instantiation is done 
HashMap<String,Person> personMap = new HashMap<String,Person>(); 
//Put the person instance in map with unique id to retrieve it back 
String personId = "CASDF125" 
Person person = new Person(); 
//set the properties in the Person instance and put it in the map 
personMap.put(personId,person); 

希望这有助于你理解!