再练
2012-04-22 20:02 Lves Li 阅读(182) 评论(0) 编辑 收藏 举报
import java.util.*;//。
import java.util.Map.Entry;
class Student implements Comparable <Student>
/*定义一个Student类覆写hashCode和equals
方法使其具有比较性继承Comparable接口实现compaeTo方法使其具有一定的排序性*/
{
//定义三个私有成员
private String name;
private int num;
private String addrees;
Student (String name,int num,String addrees)//构造函数
{
this.name=name;
this.num=num;
this.addrees=addrees;
}
public int compareTo(Student s)//实现Comparable接口中的compareTo方法
{
int a= this.name.compareTo(s.name);
if (a==0)
return new Integer(this.num).compareTo(new Integer(s.num));
return a;
}
public String getName()
{
return name;
}
public int getNum()
{
return num;
}
public String getAddrees()
{
return addrees;
}
public int hashCode()//覆写hashCode方法
{
return name.hashCode()+num*34;
}
public boolean equals(Object obj)//覆写equals方法
{
if (!(obj instanceof Student))
{
throw new ClassCastException("失败");
}
Student s=(Student)obj;
return this.name.equals(s.name)&&this.num==s.num&&this.addrees.equals(s.addrees);
}
public String toString()
{
return "学号: "+num+" 姓名: "+name+" 地址: "+addrees;
}
}
public class MapTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<Student,Integer> map=new HashMap<Student,Integer>();
map.put(new Student("Tom",001,"Baijing"), 53);
map.put(new Student("Jam",002,"Baijing"), 87);
map.put(new Student("Joy",003,"Baijing"), 96);
map.put(new Student("Pak",004,"Baijing"), 49);
//第一种取出方式 keySet方法
Set<Student> keyset=map.keySet();
Iterator it =keyset.iterator();
while (it.hasNext())
{
Student st=(Student) it.next();
Integer score=map.get(st);
System.out.println(st+":::"+score);
}
//第二种取出方式 entrySet方法
Set<Map.Entry<Student,Integer>> entryset=map.entrySet();
Iterator<Map.Entry<Student,Integer>> its =entryset.iterator();
while (its.hasNext())
{
Map.Entry<Student,Integer> mm=its.next();
Student stu= mm.getKey();
Integer sco=mm.getValue();
System.out.println(stu+" 成绩: "+sco);
}
}
}