本帖最后由 张向辉 于 2013-2-6 15:03 编辑
class Student implements Comparable<Student>
这一句话为什么一定呀加泛型不然就会出问题?
/*
2013年1月8日20:58:33(HashMapTest)
1、描述学生对象,将学生对象封装成类。
2、定义HashMap容器,将学生对象作为键,地址作为值。存入集合中
3、获取HashMap集合中的元素。
*/
import java.util.*;
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;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("非法类型输入");
Student stu = (Student)obj;
return this.name.equals(stu.name) &&this.age==stu.age;
}
public int compareTo(Student s)
{
int num = new Integer(this.age).compareTo(s.age);
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public String toString()
{
return name+":"+age;
}
}
class HashMapTest
{
public static void main(String[] args)
{
HashMap<Student,String> hm = new HashMap<Student,String>();
hm.put(new Student("zhangsan1",20),"beijing");
hm.put(new Student("zhangsan5",21),"tianjin");
hm.put(new Student("zhangsan2",23),"nanjin");
hm.put(new Student("zhangsan1",20),"dongjin");
//使用entrySet方法取出
Set<Map.Entry<Student,String>> entryset = hm.entrySet();
Iterator<Map.Entry<Student,String>> it = entryset.iterator();
while(it.hasNext())
{
Map.Entry<Student,String> me = it.next();
Student s = me.getKey();
String addr = me.getValue();
sop("Student="+s+",addr="+addr);
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
|