Java Comparator.Compareable interface

package common_class;

import java.util.Arrays;

//Compare two objects, and the one with the best score ranks first
//implement the Compareable interface
class Student implements Comparable<Student> {

	private String name;
	private int score;

	@Override
	public String toString() {
		return this.name + ", " + this.score;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		this.score = score;
	}

	public Student(String name, int score) {
		super();
		this.name = name;
		this.score = score;
	}

	//Override the compareto method
	@Override
	public int compareTo(Student s) {
		if (this.score > s.score) {
			return -1;
		}
		else if(this.score < s.score) {
			return 1;
		}else {
			return 0;
		}
	}

}

public class Compare {
	public static void main(String[] args) {
		Student[] arrs={
			new Student("Li Si", 66),
			new Student("Zhang San",58),
			new Student("Dick", 100),
			new Student("Wang Wu", 90),
			new Student("Liu", 77),
		};
		Arrays.sort(arrs);//Comparing two objects, the one with the best score ranks first
		for (int i = 0; i < arrs.length; i++) {
			System.out.println(arrs[i]);
		}
	}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326992248&siteId=291194637