Two methods of sorting ArrayList in Java and code for traversal

For a comparison of various sorting methods, see my blog:
https://blog.csdn.net/qq_37486501/article/details/80141586

method one:

  • Implement the compareTo() method in the Comparable interface in the class definition, and then call Collections.sort() to sort:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
class Student implements Comparable{//使用Comparable接口
     String name;
     int score;
    public Student(String name,int score)
    {
        this.name=name;
        this.score=score;   
    }
    @Override
    public int compareTo(Object o) {//使用Comparable的compareTo方法
        // TODO Auto-generated method stub
        Student s=(Student) o;// Object类确定为Student类
        return s.score-this.score;//决定排序的顺序
    }   
}
public class Main{
        public static void main(String[] args){

            ArrayList<Student> list=new ArrayList<Student>();
            list.add(new Student("bbb",30));
            list.add(new Student("aaa",15));
            list.add(new Student("ccc",80));
            Collections.sort(list);//排序
            Iterator<Student> it=list.iterator();//迭代器输出
            while(it.hasNext())
            {
                Student s=(Student) it.next();  //转换为Student类
                System.out.printf("%s %d\n",s.name,s.score);
        }
      }
}

Method Two:

  • Create a new class, implement Comparator, and call Collections.sort in the main function (the name of the collection to be processed, new new class())
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
class Student {
     String name;
     int score;
    public Student(String name,int score)
    {
        this.name=name;
        this.score=score;   
    }
}
class Stu implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        // TODO Auto-generated method stub
        return o1.score-o2.score;//决定排序的顺序
    }   
}

public class Main{
        public static void main(String[] args){

            ArrayList<Student> list=new ArrayList<Student>();
        list.add(new Student("bbb",30));
        list.add(new Student("aaa",15));
        list.add(new Student("ccc",80));
        Collections.sort(list,new Stu());//排序方法
            Iterator<Student> it=list.iterator();//迭代器输出
            while(it.hasNext())
            {
                Student s=(Student) it.next();  //转换为Student类
                System.out.printf("%s %d\n",s.name,s.score);
        }
      }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325532492&siteId=291194637