1. 程式人生 > >對象排序

對象排序

urn .com obj code pack res javase 接口 jdk1

參考鏈接:

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

排序的對象類型需要實現Comparable接口 或 Comparator接口


package bill99.com.jdk18;

public class Student implements Comparable<Student>{
    
    public Student(String name, int age, String className, int grade) {
        super();
        this.name = name;
        this.age = age;
        this.className = className;
        this.grade = grade;
    }
    
    
    private String name;
    private int age;
    private String className;
    
    private  int grade;
    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 getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
    
    public int getGrade() {
        return grade;
    }
    public void setGrade(int grade) {
        this.grade = grade;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((className == null) ? 0 : className.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (className == null) {
            if (other.className != null)
                return false;
        } else if (!className.equals(other.className))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    public int compareTo(Student o) {
        
        /**
         *  return (e1.number() < e2.number() ? -1 :
               (e1.number() == e2.number() ? 0 : 1));
         */
        int   result = 0;
        //判斷屬性的值的問題
        if(this.getGrade()>o.getGrade()){
            result =1;
        }
        if(this.getGrade() < o.getGrade()){
            result =-1;
        }
        return result;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", className=" + className + ", grade=" + grade + "]";
    }
    
    
    
    
}

對象排序