java中 Comparable.compareTo()与Comparator.compare()的排序顺序

使用场景

Comparable:

是interface,一般通过implements重写compareTo()方法,是自身与参数的比较
在比较时不再需要comparator

javaDoc:

int compareTo​(T o)
Compares this object with the specified object for order. 
Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

compareTo()返回正数时 this('s index) is greater than argument 调用对象的索引值大(调用对象在参数之后)

Comparator:

是interface,一般通过实现匿名内部类,重写compare(),并作为sort方法的参数实现排序,是两个参数的比较

javaDoc:

int compare​(T o1, T o2)
Compares its two arguments for order.
Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

compare()返回正数时 arg0 is greater than arg1 第一个参数的索引值大(第一个参数在第二个参数之后) (逻辑与compareTo类似)

实验验证

Person class

package bean;

public class Person implements Comparable<Person>{
	
	public int age;
	
	
	public Person(int age) {
		super();
		this.age = age;
	}


	@Override
	public int compareTo(Person o) {
		System.out.println("compareTo");
		return this.age-o.age;
	}


	@Override
	public String toString() {
		return "Person [age=" + age + "]";
	}
	

}

Main class

import java.util.ArrayList;
import java.util.Comparator;

import bean.Person;

public class Main {
	public static void main(String[] args) {
		Person p1=new Person(1);
		Person p2=new Person(2);
		Person p3=new Person(3);
		ArrayList<Person> list=new ArrayList<Person>();
		list.add(p3);
		list.add(p2);
		list.add(p1);
		list.sort(null);
		for(Person p:list) {
			System.out.println(p);
		}
		
		list.sort(new Comparator<Person>() {

			@Override
			public int compare(Person o1, Person o2) {
				System.out.println("compare");
				return o2.age-o1.age;
			}
			
		});
		for(Person p:list) {
			System.out.println(p);
		}
	}
}

实验结果

image

posted @ 2021-08-06 12:39  niu_a  阅读(360)  评论(0编辑  收藏  举报