0

## JAVA泛型問題

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapTest {
public static void main(String[] args) {

``````     People p1 = new People("001",21);
People p2 = new People("002",33);
People p3 = new People("003",41);

Map<String,People>map=new HashMap<>();
map.put("001", p1);
map.put("002", p2);
map.put("003", p3);

Set<String>keys=map.keySet();
for(String key:keys) {
System.out.println("name="+key+",age="+map.get(key));
}

}

name=001,age=People@2a139a55
name=002,age=People@15db9742
name=003,age=People@6d06d69c
``````

### 1 個回答

1
wrxue
iT邦新手 2 級 ‧ 2020-10-17 19:28:41

``````map.get(key)
``````

``````System.out.println("name="+key+",age="+map.get(key).age);
``````

wrxue iT邦新手 2 級 ‧ 2020-10-17 20:01:29 檢舉

public class People {
private String name;
private int age;

``````public People(String id, int age) {
this.name = id;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
``````

}

wrxue iT邦新手 2 級 ‧ 2020-10-17 20:08:26 檢舉

``````System.out.println("name="+key+",age="+map.get(key).getAge());
``````
wrxue iT邦新手 2 級 ‧ 2020-10-17 20:10:04 檢舉