Java 自定义排序

文章目录

  • 数组(基本数据类型)排序
  • 包装类排序
  • Java 自定义排序
    • 1、实现 Comparable 接口并重写 compareTo() 方法
    • 2、实现 Comparator 接口,重写 compare() 方法。
  • java 中同类对象之间的 compareTo() 和 compare() 方法对比分析
    • compareTo() 方法
    • compare()方法
  • Interface Comparable < T >
  • Interface Comparator
    • method

数组(基本数据类型)排序

升序排序:Arrays.sort 方法

int[] arr = {10, 3, 6, 1, 4, 5, 9};
Arrays.sort(arr); 

降序排序:升序排序,逆序访问赋值。

Arrays.sort(arr);
int[] descArray = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
        descArray[i] = array[arr.length - i - 1];
}

包装类排序

jdk 类库中的包装类已经重写了 Compare 方法,即有默认排序规则,例如对于 Integer 类型会比较其包装的值类型大小,对于 String 类型会以长度最小字符串为基准,逐一比较相同位置字符的 ASCII 码大小,如果都相同则比较字符串的长度。

以 Integer 为例子,升序排序:

// Integer 集合,升序排序
List<Integer> list = new ArrayList<Integer>(Arrays.asList(10, 3, 6, 1, 4, 5, 9));
Collections.sort(list);

降序排序:

Comparator<Integer> reverseComparator = Collections.reverseOrder();
Collections.sort(list, reverseComparator);
// Collections.sort(list, Collections.reverseOrder());

Java 自定义排序

Arrays.sort() 方法可以对原始类型(基本数据类型)和对象类型进行排序;而 Collections.sort() 只能对 List 进行排序,也是通过 Arrays.sort() 方法实现的。

java.util.Collections 中的静态方法的 Collections.sort() 主要是针对集合框架中的动态数组,链表,树,哈希表等( ArrayList、LinkedList、HashSet、LinkedHashSet、HashMap、LinkedHashMap )进行排序。

JDK 中大部分的类都实现了 Comparable 接口,拥有 compareTo 方法。如 Integer,String 等。

1、实现 Comparable 接口并重写 compareTo() 方法

int java.lang.Integer.compare(int x, int y) 

Compares two int values numerically. The value returned is identical to what would be returned by:
Integer.valueOf(x).compareTo(Integer.valueOf(y))

Parameters:
x the first int to compare
y the second int to compare

Returns:
the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y

Since:
The method compare(int, int) in the type Integer is not applicable for the arguments

2、实现 Comparator 接口,重写 compare() 方法。

将实现好的接口作为参数传入 Arrays.sort() 或 Collections.sort()。

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

String[] str = {"abc","aa","abcd","abcde","bb","abcedf"};
// 自定义排序
Arrays.sort(str, new CompLen());
// Arrays.sort(str, (a, b) -> a.length() - b.length());
System.out.println(Arrays.toString(str));
// 降序 Collections.reverseOrder()
Integer[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Arrays.sort(a, Collections.reverseOrder());

class CompLen implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
		return o1.length() - o2.length(); // 也可以实现降序排列 o2.length() - o1.length();
	}
}

compareTo(Object o) 方法是 java.lang.Comparable 接口中的方法,当需要对某个类的对象进行排序时,该类需要实现 Comparable 接口的,必须重写 public int compareTo(T o) 方法。

它强行将实现它的每一个类的对象进行整体排序-----称为该类的自然排序,实现此接口的对象列表和数组可以用 Collections.sort() 和Arrays.sort() 进行自动排序;也就是说,只要实现了这个接口的对象(数组)就相当于有了排序的能力,所以叫做 comparable —可排序的,是一种 内部排序的方式,通过实现它唯一的方法 compareTo()

compare(Object o1,Object o2) 方法是 java.util.Comparator 接口的方法,它实际上用的是待比较对象的 compareTo(Object o) 方法。
对于它,则是针对一些本身没有比较能力的对象(数组)为它们实现比较的功能,所以它叫做 比较器,是一个外部的东西,通过它定义比较的方式,再传到 Collection.sort() 和 Arrays.sort() 中对目标排序,而且通过自身的方法 compare() 定义比较的内容和结果的升降序。

java 中同类对象之间的 compareTo() 和 compare() 方法对比分析

java 中同类对象之间的比较又分为两种,基本类型之间的比较和引用类型之间的比较。

“==” 是一个比较运算符,基本数据类型比较的是值,引用数据类型比较的是地址值。(比较地址值即是指是否为同一个对象的引用)
equals() 是一个方法,只能比较引用数据类型。重写前比较的是地址值,重写后比一般是比较对象的性。

以上两种所述的方式都是只能比较对象与对象相不相等,我们往往需要的是它们之间的大小比较,当然对于基本类型值大小之间的比较,常用的是 “>”,但关于对象与对象之间的大小比较,主要有类实现 Comparable 接口(重写 compareTo() 方法),或提供 Comparator 接口(重写 compare()方 法)。

compareTo() 方法

重写 compareTo() 方法是实现 Comparable 接口的使用(自然排序)规则:如果当前对象 this 大于形参对象 obj,则返回正整数,如果当前对象 this 小于形参对象 obj, 则返回负整数。如果当前对象 this 等于形参对象 obj, 则返回零。

public class Test {
	public static void main(String[] args) {	
		Student stu1 = new Student("hubert",20);		
		Student stu2 = new Student("jake",18);		
		System.out.println(stu1.compareTo(stu2));//结果为1	
	}
}

class Student implements Comparable{
	private String name;
	private int age;
	
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	@Override
	public int compareTo(Student o) {
		return this.age
	}
}

compare()方法

重写 compare() 方法是提供 Comparator 接口的使用 (定制排序)。重写 compare(Object o1, Object o2) 方法,比较 o1 和 o2 的大小,如果方法返回正整数,则表示 o1 大于 o2, 如果返回 0,表示二者相等,如果返回负整数,表示 o1 小于 o2.

引入原因:当元素的类型没有实现 java.lang.Comparable 接口而又不方便修改代码,或者实现了 java.lang.Comparable 接口的排序规则不适合当前的操作可以考虑使用 Comparator 的对象来实现排序。

import java.util.Comparator;

public class Test {
	public static void main(String[] args) {	
		Student stu1 = new Student("hubert",20);		
		Student stu2 = new Student("jake",18);		
		int compare = new Comparator() {	
			@Override			
			public int compare(Student o1, Student o2) {			
				return o1.getAge() < o2.getAge() ? -1 : o1.getAge() == o2.getAge() ? 0 : 1;
			}
		}.compare(stu1, stu2);
		System.out.println(compare);
	}
}

class Student{
	private String name;
	private int age;
	public Student(String name, int age) {	
		this.name = name;		
		this.age = age;
	}	
	public int getAge() {	
		return age;	
	}
}

Comparator 接口有两个抽象方法,一个是 compare,另一个是 equals 方法,而写这个匿名内部类时,可以不重写 equals 方法,但所有的类都继承 Object, 所以可以不实现 equals 方法。

Module java.base Package java.lang

Interface Comparable < T >

public interface Comparable < T > This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method. Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

int compareTo(T o)
Compares this object with the specified object for order.

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.

Parameters: o - the object to be compared.
Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Throws:
NullPointerException - if the specified object is null
ClassCastException - if the specified object’s type prevents it from being compared to this object.

两个字符串比较返回 ASCII 的差。

String a = "a";
String b = "c";        
System.out.println(a.compareTo(b));

字符串和子串比较返回长度差。

String a = "a1";
String b = "a12345678";        
System.out.println(a.compareTo(b));

返回为正数表示 a > b, 返回为负数表示 a < b, 返回为 0 表示 a == b;

Error:Cannot invoke compareTo(int) on the primitive type int
只能比较引用数据类型,原生类型比较需要包装类。

模块 java.base 包 java.util

Interface Comparator

Type Parameters: T - the type of objects that may be compared by this comparator

public interface Comparator
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

method

int compare(T o1, T o2) Compares its two arguments for order.
default Comparator reversed() Returns a comparator that imposes the reverse ordering of this comparator.

static > Comparator
comparing(Function keyExtractor)
Accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key.
static Comparator comparing(Function keyExtractor, Comparator keyComparator)
Accepts a function that extracts a sort key from a type T, and returns a Comparator that compares by that sort key using the specified Comparator.
static Comparator comparingDouble(ToDoubleFunction keyExtractor)
Accepts a function that extracts a double sort key from a type T, and returns a Comparator that compares by that sort key.
static Comparator comparingInt(ToIntFunction keyExtractor)
Accepts a function that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key.
static Comparator comparingLong(ToLongFunction keyExtractor)
Accepts a function that extracts a long sort key from a type T, and returns a Comparator that compares by that sort key.
boolean equals(Object obj) Indicates whether some other object is “equal to” this comparator.
static > Comparator naturalOrder()
Returns a comparator that compares Comparable objects in natural order.
static Comparator nullsFirst(Comparator comparator)
Returns a null-friendly comparator that considers null to be less than non-null.
static Comparator nullsLast(Comparator comparator)
Returns a null-friendly comparator that considers null to be greater than non-null.

static > Comparator reverseOrder()
Returns a comparator that imposes the reverse of the natural ordering.
default Comparator thenComparing(Comparator other)
Returns a lexicographic-order comparator with another comparator.
default > Comparator
thenComparing(Function keyExtractor)
Returns a lexicographic-order comparator with a function that extracts a Comparable sort key.
default Comparator thenComparing(Function keyExtractor, Comparator keyComparator)
Returns a lexicographic-order comparator with a function that extracts a key to be compared with the given Comparator.
default Comparator thenComparingDouble(ToDoubleFunction keyExtractor)
Returns a lexicographic-order comparator with a function that extracts a double sort key.
default Comparator thenComparingInt(ToIntFunction keyExtractor)
Returns a lexicographic-order comparator with a function that extracts an int sort key.
default Comparator thenComparingLong(ToLongFunction keyExtractor)
Returns a lexicographic-order comparator with a function that extracts a long sort key.

你可能感兴趣的:(Java,基础,java,开发语言,后端)