黑马程序员技术交流社区

标题: 集合框架中3个需要重写的方法 [打印本页]

作者: shengdong521    时间: 2016-6-13 23:47
标题: 集合框架中3个需要重写的方法
在这里总结下3个一般需要重写的方法。需要按照自己的需求重写,这里举例说明下。
1,hashcode重写
public int hashcode()
{
     return name.hashcode() + age*21;
}
2,equals重写
public boolean equals(Object obj)
{
     if(!(obj instanceof Student))
          throw new RuntimeException;
     Student s=(Student)obj;
     return this.name.equals(s.name) && this.age==s.age;
}
3compareTo重写(先按年龄排序,年龄相同再按姓名)
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;
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2