为什么要覆盖hashcode? 又没有tree
import java.util.*;
class MapTestDemo
{
public static void main(String[] args)
{
Map<Student,String> student=new HashMap<Student,String>();//创建Map集合
student.put(new Student("aaa",20),"henan");
student.put(new Student("aaa",20),"henan");
student.put(new Student("aaa",20),"henan");
student.put(new Student("ccc",22),"北京");
Set<Student> set=student.keySet();//获取键的集合
Iterator<Student> it=set.iterator();//创建一个迭代器
while(it.hasNext())
{
Student p=it.next();
String value=student.get(p);
System.out.println(p.getName()+"..."+p.getAge()+"..."+value);
}
}
}
class Student implements Comparable<Student>//实现 和 覆盖两个方法 为什么要实现Comparable?
//为什么还要覆盖呢,这两个有什么区别
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=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 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 s=(Student)obj;
return this.name.equals(s.name) && this.age==s.age;
}
}
|