HashMap集合存储学生对象并遍历

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

public class MapDemo {
	public static void main(String[] args) {
		//创建HashMap集合对象
		HashMap<String, Student> hm = new HashMap<String,Student>();
		//创建学生对象
		Student s1=new Student("王祖贤",20);
		Student s2=new Student("张曼玉",21);
		Student s3=new Student("林青霞",22);
		//把学生类添加到集合
		hm.put("001", s1);
		hm.put("002", s2);
		hm.put("003", s3);
		
		//遍历方式1:键找值
		Set<String> keySet = hm.keySet();
		for(String key:keySet) {
			Student value=hm.get(key);
			System.out.println(key+","+value.getName()+","+value.getAge());
		}
		System.out.println("--------------");
		
		//遍历方式2:键值对对象找键和值
		Set<Entry<String, Student>> entrySet = hm.entrySet();
		for(Entry<String, Student> me:entrySet) {
			String key=me.getKey();
			Student value=me.getValue();
			System.out.println(key+","+value.getName()+","+value.getAge());
		}
	}

}

public class Student {
	private String name;
	private int age;
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(String name, int age) {
		super();
		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;
	}
	

}

上一篇:鼠标拖拽点击脚本


下一篇:位运算的应用