排序之比较器Comparable<T>
大约 2 分钟
一、Comparable比较器的使用
JAVA中可以通过实现 Comparable接口的方式让对象进行排序。使用方法:
1、实体继承Comparable
2、实现compareTo方法,根据需求进行比较
package com.bjut.fight.utils.comparable;
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
// 1表示大于,-1表示小于,0表示等于
return this.age >= o.age ? 1 : -1;
}
public void print() {
System.out.println(this.name + "," + this.age);
}
}
public class Test {
public static void main(String[] args) {
Student stu1 = new Student("zhangsan", 10);
Student stu2 = new Student("zhangsan", 21);
Student stu3 = new Student("zhangsan", 19);
Student stu4 = new Student("zhangsan", 26);
Student[] students = {stu1, stu2, stu3, stu4};
Arrays.sort(students);
for (Student stu : students) {
stu.print();
}
}
}
二、Comparable 比较器的原理
为什么实现compareTo两个元素比较,不需要扫描全部,下一个元素插入的时候就把顺序排好了,它使用的是二叉树中序排序,下边是(网上最多介绍的)简单的处理方法:
(1)设置根节点
(2)新增节点,与根节点比较大小,
小则放到左子树(若左子树已经存在,则用此左子树进行递归调用)
大则放到右子树(若右子树已经存在,则用此右子树进行递归调用)
package com.bjut.fight.utils.comparable;
/**
* @author zheng on 2020/1/2 9:26
*/
public class MyComparable {
public static class BinaryTree<T> {
class Node {
private Comparable<T> data;
private Node left;
private Node right;
Node(Comparable<T> data) {
this.data = data;
}
void addNode(Node newNode) {
if (newNode.data.compareTo((T) this.data) < 0) {
if (this.left == null) {
this.left = newNode;
} else {
this.left.addNode(newNode);
}
}
if (newNode.data.compareTo((T) this.data) >= 0) {
if (this.right == null) {
this.right = newNode;
} else {
this.right.addNode(newNode);
}
}
}
void print() {
if (this.left != null) {
left.print();
}
System.out.println(this.data + "\t");
if (this.right != null) {
this.right.print();
}
}
}
private Node root;
public void add(Comparable<T> data) {
Node newNode = new Node(data);
if (root == null) {
root = newNode;
} else {
root.addNode(newNode);
}
}
public void print() {
this.root.print();
}
}
}
public class Test {
public static void main(String[] args) {
MyComparable.BinaryTree<Integer> bt = new MyComparable.BinaryTree<>();
bt.add(1);
bt.add(2);
bt.add(0);
bt.print();
}
}