/*每一个学生都有对应归属地
* 学生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;
}
}
[黑马程序员]集合map练习
最新推荐文章于 2014-04-19 22:48:51 发布