Student.java
Java Core
package CompareSort; public class Student implements Comparable < Student > { private String name; private String address; 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 getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Student(String name, String address, int age) { super(); this.name = name; this.age = age; this.address = address; } public Student() { super(); } @Override public int compareTo(Student o) { int sizeName = this.name.compareTo(o.name); if (sizeName != 0) { return sizeName; } int sizeAddress = this.address.compareTo(o.address); if (sizeAddress != 0) { return sizeAddress; } return this.age - o.age; } }
main.java
Java Core
package CompareSort; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { Student a = new Student("A", "B", 6); Student b = new Student("C", "B", 5); Student c = new Student("C", "B", 3); Student d = new Student("A", "B", 1); Student e = new Student("C", "B", 4); Student f = new Student("A", "B", 7); ArrayList<Student> list = new ArrayList<Student>(); list.add(a); list.add(b); list.add(c); list.add(d); list.add(e); list.add(f); Collections.sort(list); for (Student ss : list) { System.out.println(" Name: " + ss.getName() + " Address: " + ss.getAddress() + " Age: " + ss.getAge()); } } }
Trường hợp thay đổi giá trị thứ tự sắp xếp ưu tiên
Name > Address > Age
Name > Address > Age
Nếu Name trùng nhau thì sẽ ưu tiến sắp xếp theo Address
Nếu Name và Address có tên trùng nhau thì ưu tiên cuối cũng sẽ sắp xếp theo Age
0 nhận xét:
Post a Comment