Java uses compareTo to compare the size of objects of a class

First define an object, note that this object must implement the Comparable interface and override the compareTo method of this interface

package cn.demo;

public class Student implements Comparable{
	private int number=0; //student number
	private String name=""; //Student name
	private String gender=""; //gender
	public int getNumber(){
		return number;
	}
	public void setNumber(int number){
		this.number=number;
	}
	public String getName(){
		return name;
	}
	public void setName(String name){
		this.name=name;
	}
	public String getGender(){
		return gender;
	}
	public void setGender(String gender){
		this.gender=gender;
	}
	
	public int compareTo(Object obj){
		Student student=(Student)obj;
		if(this.number==student.number){  
			return 0; //If the student number is the same, then the two are equal
		}else if(this.number>student.getNumber()){ 
			return 1; //If the student ID of this student is greater than the student ID of the incoming student
		}else{
			return -1; //If the student ID of this student is less than the student ID of the incoming student
		}
	}
}
In the place marked red in the above rewrite method, if it is less than sign, it is in descending order, but in the code I posted, it is in ascending order

Next is the test class:

package cn.demo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class Test {
	public static void main(String[] args) {
		Student student1=new Student();
		student1.setNumber (5);
		Student student2=new Student();
		student2.setNumber (2);
		Student student3=new Student();
		student3.setNumber (1);
		Student student4=new Student();
		student4.setNumber (4);
		ArrayList<Student> list=new ArrayList<Student>();
		list.add(student1);
		list.add(student2);
		list.add(student3);
		list.add(student4);
		System.out.println("-------before sorting-------");
		Iterator<Student> iterator=list.iterator();
		while(iterator.hasNext()){
			Student stu=iterator.next();
			System.out.println(stu.getNumber());
		}
		//Use the sort method of Collections to sort the list
		System.out.println("-------after sorting-------");
		Collections.sort(list);
		iterator=list.iterator();
		while(iterator.hasNext()){
			Student stu=iterator.next();
			System.out.println(stu.getNumber());
		}

	}
}

As shown above, you can directly use the sort method of collections to sort

-------Before sorting -------
5
2
1
4
-------After sorting -------
5
4
2
1

Guess you like

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