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

HashMap hashKey = new HashMap();의 HashMap과 뽀조

은 그들에게

을 얻을하고는 도움을 나에게 줄 수있는 방법을

+1

귀하의 노력은 어디에 있습니까? –

+0

"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의 값은입니다.유형의 경우 해당 인물 인스턴스를 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은 유형에 대해 매개 변수화 된 일반 클래스입니다. 당신은 아주 잘 문자열 유형 또는 비 원시적 형이 당신이 이해하는 데 도움이

//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); 

희망으로 키와 형식 매개 변수에 POJO 유형의 사용을 만들 수 있습니다!

관련 문제