Java natural sorting Comparable use method analysis

First, explain that when using the TreeSet collection to store customizations, the parameterless construction method uses natural sorting to sort the elements

Then, the premise of using natural ordering is that the class to which the element belongs implements the Comparable interface and rewrites the comparaTo(T o) method.

Secondly, it should be noted that when rewriting the method, it must be noted that the sorting rules must be written in accordance with the main conditions and conditions required. Let's implement it through a requirement.

Requirements: Store and traverse student objects, create a TreeSet collection using no-parameter construction method.

Requirement: Sort by age from youngest to oldest. When the age is the same, sort by alphabetical order of names

The analysis shows that two classes are needed: a student class (Student) and an operation class (TreeSetDemo). There are two member traversals in the student class: name (name) and age (age). (Only record the rewrite code part)

Operation code:

public class TreeSetDemo {
  public static void main(String[] args) {
    //创建集合对象
    TreeSet<Student> treeSet = new TreeSet<Student>();

    //创建学生对象
    Student s1 = new Student("xishi",29);
    Student s2 = new Student("wangzhaojun",30);
    Student s3 = new Student("diaocan",28);
    Student s4 = new Student("yangyuhuan",31);

    //添加元素
    treeSet.add(s1);
    treeSet.add(s2);
    treeSet.add(s3);
    treeSet.add(s4);

    //遍历
    for (Student s : treeSet){
      System.out.println(s);
    }
  }
}

Next test, after implementing the Comparable interface in the student class and rewriting the compareTo(T o) method, the operation of the operation class

Rewrite the compareTo(T o) method code in the Student class: (The sort result is affected by the difference in the return value, depending on the running result)

@Override
  public int compareTo(Student o) {
    return 0;
  }
  /*
    运行结果:xishi,29
   */

@Override
  public int compareTo(Student o) {
    return 1;
  }
  /*
    运行结果:
        xishi,29
        wangzhaojun,30
        diaocan,28
        yangyuhuan,31
   */

@Override
  public int compareTo(Student o) {
    return -1;
  }
  /*
    运行结果:
        yangyuhuan,31
        diaocan,28
        wangzhaojun,30
        xishi,29
   */

By modifying the return value three times, conclusions can be drawn from the running results:

When the return value is 0, it is considered a repeated element and no storage is performed.

When the return value is 1, according to the storage order, forward sort (ascending order) (because it is a forward sort, the order from small to large can be understood)

When the return value is -1, sort in reverse order (descending order) according to the storage order (similarly)

Therefore, different sorting results can be controlled by controlling the difference in the return value. Next, realize the above requirements.

The compareTo method is being modified, so that the age is sorted in ascending order. The code:

@Override
  public int compareTo(Student s) {
    int num = this.age - s.age;
    return num;
  }
  /*
    运行结果:
        diaocan,28
        xishi,29
        wangzhaojun,30
        yangyuhuan,31
   */

Next, complete the requirements. When the ages are the same, they are sorted in alphabetical order of names. The complete code is as follows:

//操作类代码
public class TreeSetDemo {
  public static void main(String[] args) {
    //创建集合对象
    TreeSet<Student> treeSet = new TreeSet<Student>();

    //创建学生对象
    Student s1 = new Student("xishi",29);
    Student s2 = new Student("wangzhaojun",30);
    Student s3 = new Student("diaocan",28);
    Student s4 = new Student("yangyuhuan",31);
    Student s5 = new Student("linqingxia",31);

    //添加元素
    treeSet.add(s1);
    treeSet.add(s2);
    treeSet.add(s3);
    treeSet.add(s4);
    treeSet.add(s5);

    //遍历
    for (Student s : treeSet){
      System.out.println(s.getName()+","+s.getAge());
    }
  }
}

//学生类中重写代码部分及运行结果
@Override
  public int compareTo(Student s) {
    int num = this.age - s.age;
    //如果年龄相同则比较姓名字母顺序(升序)排列。
    int num2 = num == 0 ? this.name.compareTo(s.name) : num;
    return num2;
  }
  /*
    运行结果:
        diaocan,28
        xishi,29
        wangzhaojun,30
        linqingxia,31
        yangyuhuan,31
   */

Some high-frequency interview questions collected in the latest 2020 (all organized into documents), there are many dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations, as well as detailed learning plans, interviews Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/113944738