1),先获取键的集合,然后根据键找值;
(2),先获取每一个键值对,在获取每一个键和值
public class Test{
public static void main(String[] args) {
//创建集合对象
HashMap map=new HashMap();
//创建元素对象
Person p1=new Person("梁朝伟",53);
Person p2=new Person("刘德华",54);
Person p3=new Person("汤镇业",56);
Person p4=new Person("苗侨伟",47);
Person p5=new Person("黄日华",53);
//将元素添加到集合当中
map.put(p1, "无线");
map.put(p2, "有线");
map.put(p3, "刘备");
map.put(p4, "关羽");
map.put(p5, "无线");
//通过获取键的集合,遍历见得集合,通过键找值
Set set = map.keySet();
for(Person key:set){
String value=map.get(key);
System.out.println(key+":"+value); }
System.out.println("===============================");
//通过键值对一一获取键和值
Set> entrySet = map.entrySet();
for (Entry entry : entrySet) {
Person key=entry.getKey();
String value=entry.getValue();
System.out.println(key+":"+value);
}
}
}
//创建元素类
class Person{
private String name;
private int age;
public Person() { }
public Person(String name, int age) {
this.name = name;
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;
}
public String toString() {
return this.name+":"+this.age;
}
} |
|