[黑马程序员]集合map练习

/*每一个学生都有对应归属地
 * 学生Student,地址String
 * 学生属性:姓名,年龄
 * 注意:姓名和年龄相同的视为同一个学生。
 * 保证学生唯一性。
 * 
 * 1.描述学生
 * 2.定义map容器。将学生作为键,地址作为值,存入。
 * 3.获取map集合中的元素
 * 
 * 
 * 
 * 注意: 覆写两个方法:hashCode, equals --》给hashCode用
 *     实现一个接口: Comparable  --》给二叉树用
 */
package test.itheima;

import java.util.*;

public class MapTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		TreeMap<MapTest_Student, String> tm = new TreeMap<MapTest_Student, String>();

		tm.put(new MapTest_Student("zhang3", 3), "北京");
		tm.put(new MapTest_Student("zhang3", 4), "北京");
		tm.put(new MapTest_Student("tom", 32), "qingdao");

		// 取出方式keySet
		Iterator<MapTest_Student> it2 = tm.keySet().iterator();
		System.out.println("第一种方法");
		while (it2.hasNext()) {
			MapTest_Student mts = it2.next();

			System.out.println(mts.getName() + ":" + mts.getAge() + ":"
					+ tm.get(mts));
		}

		
		// 取出方式entrySet
		Set<Map.Entry<MapTest_Student, String>> tmSet = tm.entrySet();

		Iterator<Map.Entry<MapTest_Student, String>> it = tmSet.iterator();
		System.out.println("第二种方法");
		while (it.hasNext()) {
			Map.Entry<MapTest_Student, String> tmpTreeMap = it.next();

			String addr = tmpTreeMap.getValue();
			int age = tmpTreeMap.getKey().getAge();
			String name = tmpTreeMap.getKey().getName();

			System.out.println(name + ":" + age + ":" + addr);
		}

	}
}

class MapTest_Student implements Comparable<MapTest_Student> {
	private String name;
	private int age;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setAge(int age) {
		this.age = age;
	}

	MapTest_Student(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return name + ":" + age;
	}

	// 给hashCode用
	public int hashCode() {
		return name.hashCode() + age * 34;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof MapTest_Student)) {
			throw new ClassCastException("类型不匹配");
		}
		MapTest_Student s = (MapTest_Student) obj;

		return this.name.equals(s.name) && this.age == s.age;

	}

	// 给二叉树用
	@Override
	public int compareTo(MapTest_Student o) {
		int num = new Integer(this.age).compareTo(new Integer(o.age));
		if (num == 0)
			return this.name.compareTo(o.name);
		return num;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值