关于java的集合

wy901024 2012-10-04 10:36:28
import java.util.*;
public class MapDemoTest {

/**
* @param args
*/
public static void main(String[] args) {
HashMap<Student,String> m = new HashMap<Student,String>();
m.put(new Student("lisi",11),"China");
m.put(new Student("lisi",11),"China");
m.put(new Student("lisi",12),"China");
m.put(new Student("lisi",13),"China");
Set<Map.Entry<Student,String>> sm = m.entrySet();
Iterator<Map.Entry<Student,String>> it = sm.iterator();
while(it.hasNext())
{
Map.Entry<Student,String> ms = it.next();
Student stu = ms.getKey();
String addr = ms.getValue();
System.out.println(stu+"-----"+addr);
}
}

}

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 void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString()
{
return name+":"+age;
}

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;
}
public int hashCode()
{
return age*3;

}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("内型不匹配");
Student s = (Student)obj;
return this.name.equals(s.name)&&this.age == s.age;
}

}

这段代码里为什么要实现 Comparable接口,我感觉之重写equals和hashCode()两个方法足够了啊!他这个compareTo方法在这里有什么用啊?
...全文
93 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
liangtu 2012-10-04
  • 打赏
  • 举报
回复
同楼上,这是为了比较两个对象。
jijihahalala 2012-10-04
  • 打赏
  • 举报
回复
实现 Comparable接口是为了对放入map的key进行排序,先根据age排,如果相等根据name,重写equals和hashCode()是否是相等
diypyh 2012-10-04
  • 打赏
  • 举报
回复
Comparable是定义排序的规则

equals和hashCode是定义比较的规则

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧