本帖最后由 杨栋 于 2013-8-23 17:18 编辑
/**
练习:
1.每一个学生都有对应的归属地
2.学生student,归属地String
3.学生属性 姓名 年龄
4.学生姓名和年龄相同视为同一个学生
5.保证学生的唯一性
要求:
1.描述学生
2.定义map容器,学生视为键,地址视为值,存入
3.获取map中的元素
*/
import java.util.*;
class StudentDemo
{
public static void main(String[] args)
{
//建立HashMap,用哈希集合来存储元素
HashMap<Student,String> hs=new HashMap<Student,String>();//此Map集合的键类型是Student,值类型是String;这就是泛型
hs. put(new Student("zhansan1",16),"shanxi");
hs. put(new Student("zhansan2",13),"jiangxi");
hs. put(new Student("zhansan4",17),"hebei");
hs. put(new Student("zhansan1",20),"aomen");
//通过键的集合来获取元素
Set<Student> keySet=hs.keySet();
Iterator<Student> it=keySet.iterator();
while(it.hasNext())
{
Student key=it.next();
String src=hs.get(key);
System.out.println(key.getName()+":"+key.getAge()+"--"+src);
}//end 通过键来获取值
//通过关系来获取元素
Set<Map.Entry<Student,String>> entry=hs.entrySet();
Iterator<Map.Entry<Student,String>> itgx=entry.iterator();
while(itgx.hasNext())
{
Map.Entry<Student,String> elen=itgx.next();
String src1=elen.getValue();
Student stu=elen.getKey();
System.out.println(stu.getName()+":"+stu.getAge()+"--"+src1+"通过关系获取元素");
}//end 通过关系来获取值
//end HashMap
System.out.println("--------------下面是TreeMap-------------------");
//建立TreeMap集合 用二叉树来存储元素
TreeMap<Student,String> tm=new TreeMap<Student,String>();
tm.put(new Student("张三1",18),"上海");
tm.put(new Student("张三3",19),"咸阳");
tm.put(new Student("张三2",18),"广东");
//通过keySet()键的集合来获取元素
Set<Student> keyset2=tm.keySet();
Iterator it2=keyset2.iterator();
while(it2.hasNext())
{
Student key2=(Student)it2.next();
String src2=tm.get(key2);
System.out.println("二叉树--"+key2.getName()+":"+key2.getAge()+":"+src2);
}//end 通过键来获取值
//通过关系来获取元素
Set<Map.Entry<Student,String>> elen2=tm.entrySet();
Iterator<Map.Entry<Student,String>> it3=elen2.iterator();
while(it3.hasNext())
{
Map.Entry <Student,String> element=it3.next();
Student stu2=element.getKey();
String src3=element.getValue();
System.out.println("二叉树--"+stu2.getName()+":"+stu2.getAge()+":"+src3+"通过关系获取元素");
}
}
}
class Student implements Comparable<Student>
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
//如果用HashMap集合那么就得重写hashCode()和equals()
public int hashCode()//哈希值决定了元素存放的位置
{
return name.hashCode()+age*39;
}
public boolean equals(Object obj)//如果哈希值相同再判断equals是否相同,如果equals返回值是true则说明是同一个人,就不进行存储
{
if(!(obj instanceof Student))//obj是当前要被存入集合中的对象,所以先判断是不是学生类,不是就直接不用比较了
return false;
Student s=(Student)obj;//向下转型 因为Object中没有getName()方法
return this.name.equals(s.name)&&(this.age==s.age);
}//end
//如果用TreeMap集合存贮元素,那么就得实现ComparrTo然后重写CompareTo()
public int compareTo(Student s)//此方法是用来保证元素唯一性的
{
int num=new Integer(this.age).compareTo(new Integer(s.age));//判断年龄
if(num==0)//如果年龄相同再判断姓名
return this.name.compareTo(s.name);
return num;
}
}
|