A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© _J2EE_LiXiZhen 中级黑马   /  2017-11-16 22:49  /  883 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

[Java] 纯文本查看 复制代码
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

//HashMap存储键是String值是自定义对象
//每位学生(姓名,年龄)都有自己的家庭住址。
//那么,既然有对应关系,则将学生对象和家庭住址存储到Map集合中。
//家庭住址作为键, 学生作为值。并使用keySet和entrySet方式遍历Map集合

public class Test06 {
	public static void main(String[] args) {
		HashMap<String, Student> map = new HashMap<String, Student>();
		// 将学生对象和家庭住址存储到Map集合中。
		map.put("北京", new Student("张三", 18));
		map.put("上海", new Student("李四", 19));
		map.put("广州", new Student("王五", 20));
		map.put("深圳", new Student("赵六", 21));
		// 使用keySet和entrySet方式遍历Map集合
		for (String key : map.keySet()) {
			System.out.println(key + "=" + map.get(key).toString());
		}

		System.out.println("==============");
		
		Set<Map.Entry<String, Student>> set2 = map.entrySet();
		for (Map.Entry<String, Student> entry : set2) {
			System.out.println(entry.getKey() + "=" + entry.getValue().toString());
		}
	}
}

public class Student {
	private String name;
	private int age;
	public Student() {
		super();
	}
	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;
	}
	
	public String toString() {
		return ("["+name+" , "+age+"]");
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马