(Comparator) Comparator problem leads to

Comparator problem leads to

The so-called comparator is to determine the size relationship, let's first analyze the meaning of the comparator:

If you want to perform array operations, you must use the java.util.Arrays operation class to complete, this class provides most of the array operation support, and there is also a sort of object array support in this class: public static void sort (Object[] a);

Example: Realizing the sorting of an array of objects

package 开发支持类库;

import java.util.Arrays;

public class 比较器问题的引出 {
	public static void main(String[] args) {
		Integer[] data = new Integer[] {10,8,9,4,3};	//对象数组
		Arrays.sort(data);	//进行对象数组的排序
		System.out.println(Arrays.toString(data));	//输出
	}
}

[3, 4, 8, 9, 10]

If the given array is a String object array, it can also be sorted.

Example: Sorting an array of String objects

package 开发支持类库;

import java.util.Arrays;

public class 比较器问题的引出 {
	public static void main(String[] args) {
		String[] data = new String[] {"X","x","中","Y","y"};	//对象数组
		Arrays.sort(data);	//进行对象数组的排序
		System.out.println(Arrays.toString(data));	//输出
	}
}

[X, Y, x, y, 中]

Both Java.lang.Integer and java.lang.String are program classes provided by the system. If there is a custom class that needs to be sorted.

Example: Sort by custom type

 

package 开发支持类库;

import java.util.Arrays;

public class 比较器问题的引出 {
	public static void main(String[] args) {
		Person[] data = new Person[] {
				new Person("王五",19),
				new Person("张三",80),
				new Person("李四",41),
				new Person("周一",50)
			};
		Arrays.sort(data);	//进行对象数组的排序
		System.out.println(Arrays.toString(data));	//输出
	}
}

class Person{
	private String name;
	private int age;
	
	public Person(String name,int age) {
		this.name = name;
		this.age = age;
	}
	
	//setter、getter略
	public String toString() {
		return "【Person类对象】姓名:"+this.name +"、年龄:"+this.age;
	}
}

Exception in thread "main" java.lang.ClassCastException: class 开发支持类库.Person cannot be cast to class java.lang.Comparable

By default, any class cannot be sorted or compared using the internal classes of the system, because there is no clear definition of how to compare (there is no comparison rule), so at this time in Java, in order to unify the rules The definition of, so it provides a comparator interface: Comparable interface.

Guess you like

Origin blog.csdn.net/weixin_46245201/article/details/112603569