欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 两种比较器的区别:Comparable 与 Comparator

程序员文章站 2022-06-19 15:20:02
Comparablejava.lang.comparable :是在一个类定义的时候默认实现好的接口, 里面存在有一个 compareTo() 方法实现案例package com.cwq.beyond;import java.text.SimpleDateFormat;import java.util.Arrays;class Person implements Comparable{private String name;private int ag...

Comparable

java.lang.comparable :
是在一个类定义的时候默认实现好的接口, 里面存在有一个 compareTo() 方法

实现案例

package com.cwq.beyond;

import java.text.SimpleDateFormat;
import java.util.Arrays;

class Person implements Comparable<Person>{

	private String name;
	private int age;
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	@Override
	public int compareTo(Person o) {
		if (this.age > o.age) {
			return 1;
		}else if (this.age < o.age) {
			return -1;
		}else {
			return 0;
		}
	}
	
}

public class TestDemo {
	public static void main(String[] args) throws Exception {

		Person p[] = new Person[] {
				new Person("张三", 20) ,
				new Person("张四", 18) ,
				new Person("王五", 19) ,
		};
		Arrays.sort(p);
		System.out.println(Arrays.toString(p));
		
	}

}

Java  两种比较器的区别:Comparable 与 Comparator

Comparator

java.util.comparator:
是进行挽救的比较接口, 需要单独定义一个比较规则类, 定义有 compare() 方法, equals() 方法

实现案例

package com.cwq.beyond;

import java.util.Arrays;
import java.util.Comparator;

class Person{
	private String name;
	private int age;
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public int getAge() {
		return age;
	}
	public String getName() {
		return name;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	
}

class PersonComparator implements Comparator<Person>{

	@Override
	public int compare(Person o1, Person o2) {
		if (o1.getAge() > o2.getAge()) {
			return 1;
		}else if (o1.getAge() < o2.getAge()) {
			return -1;
		}
		return 0;
		
	}
	
}

public class ComparatorDemo {
	public static void main(String[] args) {
		Person data[] = new Person[]{
			new Person("张三", 18),
			new Person("王宏", 55),
			new Person("王五", 19)
		};
		Arrays.sort(data,new PersonComparator());
		System.out.println(Arrays.toString(data));
	}
}

Java  两种比较器的区别:Comparable 与 Comparator

本文地址:https://blog.csdn.net/Beyond_Nothing/article/details/110870896