本帖最后由 403383221 于 2013-4-29 10:10 编辑
- <p>public class Student implements Comparable<Student>{
- private String name;
- private int 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 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;
- }
- public int compareTo(Student arg0) {
- int num = new Integer(this.age).compareTo(new Integer(arg0.age));
- //int num = this.age-arg0.age;为啥不直接这样写??????
- if(num == 0){
- return this.name.compareTo(arg0.name);
- }
- return num;
- }
-
- }
- </p>
复制代码 这是Map集合的练习,为了让学生类具备可比较性,实现了 Comparable接口,我想问的是,重写compareTo()时
int num = new Integer(this.age).compareTo(new Integer(arg0.age));
为啥不直接这样写??????
int num = this.age-arg0.age;
|