Comparable and Comparator of Java
Collections
Speak Comparable
with Comparator
before to talk about it Collections
, and then leads Comparable
to Comparator
.
definition:
Collection tool class, used to operate the collection.
Some methods are as follows:
public static boolean addAll(Collection c, T… elements) | Add some elements to the collection |
---|---|
public static void shuffle(List<?> list) | Shuffle the collection order |
public static void sort(List list) | Sort the elements in the collection according to the default rules |
public static void sort(List list,Comparator<? super T> ) | Sort the elements in the collection according to the specified rules |
代码演示:
public class CollectionsDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
//原来写法
//list.add(12);
//list.add(14);
//list.add(15);
//list.add(1000);
//采用工具类 完成 往集合中添加元素
Collections.addAll(list, 5, 222, 1,2);
System.out.println(list);
//排序方法
Collections.sort(list);
System.out.println(list);
}
}
结果:
[5, 222, 1, 2]
[1, 2, 5, 222]
The collection is arranged in order, but this order is the default order. What if you want to specify the order? We can use
Comparable
withComparator
Speaking of sorting, to put it simply is to compare the size of two objects, then there are two ways to implement comparison in JAVA, one is
More rigid using
java.lang.Comparable
interfaces to achieve, one is flexible when I need to do to sort of go in when selectingThe
java.util.Comparator
interface to complete.
Comparable comparator
definition:
This interface imposes an overall ordering on the objects of each class that implements it. This ordering is called the natural ordering of the class, and the compareTo
method of the class is called its natural comparison method .
compareTo
Can be rewritten to achieve custom sorting.
Comparator
definition:
The comparison function imposes an overall ordering on the collection of some objects .
The method of comparison is::
public int compare(String o1, String o2)
Compare the order of its two parameters.
There are three results of comparing two objects: greater than, equal to, and less than.
If you want to sort in ascending order,
Then o1 is less than o2, return (negative number), equal return 0, 01 is greater than 02 return (positive number)
If you want to sort in descending order
Then o1 is less than o2, return (positive number), return 0 if equal, return 01 greater than 02 (negative number)
Briefly describe the difference between the Comparable and Comparator interfaces.
Comparable : Forcibly sort the objects of each class that implements it. This sorting is called the natural sorting of classes,
compareTo
The method is called its natural comparison method. It can only be implemented compareTo()
once in the class, and the code of the class cannot be modified frequently
Realize the sort you want. The list of objects (and arrays) that implement this interface can be entered through Collections.sort
(and Arrays.sort
)
Rows are automatically sorted, and objects can be used as keys in an ordered map or elements in an ordered set without specifying a comparator.
The Comparator forcibly sorts an object as a whole. You can Comparator
pass to sort
methods (such as Collections.sort
or Arrays.sort
) to allow precise control over the sort order. It can also be used Comparator
to control the order of certain data structures (such as ordered set
or ordered mapping), or to collection
provide sorting for objects that do not have a natural order .
Question example
Use an example to illustrate
Title: respectively
Comparable
andComparator
the two interfaces do the following descending order of four students achievement, if the same results, that sort ascending according to age on the basis of the results of the sort
代码演示:
package com.Leve.Leve4.Leve4_3;
import java.util.*;
//实现Comparable接口
class Student implements Comparable<Student> {
private String name;
private int age;
private double grades;
public Student(String name, int age, double grades) {
this.name = name;
this.age = age;
this.grades = grades;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", grades=" + grades +
'}';
}
public void setGrades(float grades) {
this.grades = grades;
}
public double getGrades() {
return grades;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Double.compare(student.grades, grades) == 0 && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, grades);
}
/**
* 重写compareTo方法
* @param o
* @return
*/
@Override
public int compareTo(Student o) {
//降序
if (this.grades > o.grades)
return -1;
else if (this.grades == o.grades)
return 0;
return 1;
}
}
public class Demo4 {
public static void main(String[] args) {
TreeSet<Student> data = new TreeSet<>(new Comparator<Student>() {
/**
* 使用compare方法进行年龄排序
* 如果成绩相等,则按年龄从小到大排序
* @param o1
* @param o2
* @return
*/
@Override
public int compare(Student o1, Student o2) {
int n1 = (int) (o1.getGrades() - o2.getGrades());
int n2 = o1.getAge() - o2.getAge();
return n1 == 0 ? n2 : (n1 * (-1));
}
});
Student s1 = new Student("张三", 21, 92.5);
Student s2 = new Student("李四", 17, 85.6);
Student s3 = new Student("王五", 18, 92.5);
Student s4 = new Student("麻子", 15, 93.6);
data.add(s1);
data.add(s2);
data.add(s3);
data.add(s4);
for (Student s : data) {
System.out.println(s);
}
}
}
结果:
Student{
name='麻子', age=15, grades=93.6}
Student{
name='王五', age=18, grades=92.5}
Student{
name='张三', age=21, grades=92.5}
Student{
name='李四', age=17, grades=85.6}