• java学习笔记13--比较器(Comparable、Comparator)


    java学习笔记13--比较器(Comparable、Comparator)

    分类: JAVA

    Comparable接口的作用

    之前Arrays类中存在sort()方法,此方法可以直接对对象数组进行排序。

    Comparable接口

    可以直接使用java.util.Arrays类进行数组的排序操作,但对象所在的类必须实现Comparable接口,用于指定排序接口。

    Comparable接口的定义如下:

    public  interface  Comparable<T>{

            public  int compareTo(T  o);

    }

    此方法返回一个int类型的数据,但是此int的值只能是一下三种:

    1:表示大于

    -1:表示小于

    0:表示相等

    要求:定义一个学生类,里面有姓名,年龄,成绩三个属性,要求按成绩由高到低排序,如果成绩相等,则按照年龄由低到高排序。

    1. package com.itmyhome;  
    2.   
    3. import java.util.Arrays;  
    4.   
    5. class Student implements Comparable<Student>{  
    6.     private String name;  
    7.     private int age;  
    8.     private float score;  
    9.       
    10.     public Student(String name,int age,float score){  
    11.         this.name = name;  
    12.         this.age = age;  
    13.         this.score = score;  
    14.     }  
    15.       
    16.     @Override  
    17.     public int compareTo(Student stu) {  //覆写compareTo方法实现排序规则的应用  
    18.         if(this.score>stu.score){  
    19.             return -1;  
    20.         }else if(this.score<stu.score){  
    21.             return 1;  
    22.         }else{  
    23.             if(this.age>stu.age){  
    24.                 return 1;  
    25.             }else if(this.age<stu.age){  
    26.                 return -1;  
    27.             }else{  
    28.                 return 0;  
    29.             }  
    30.         }  
    31.     }  
    32.       
    33.     public String toString(){  
    34.         return "姓名:"+this.name+", 年龄:"+this.age+", 成绩:"+this.score;  
    35.     }  
    36.       
    37.     public String getName() {  
    38.         return name;  
    39.     }  
    40.     public void setName(String name) {  
    41.         this.name = name;  
    42.     }  
    43.     public int getAge() {  
    44.         return age;  
    45.     }  
    46.     public void setAge(int age) {  
    47.         this.age = age;  
    48.     }  
    49.     public float getScore() {  
    50.         return score;  
    51.     }  
    52.     public void setScore(float score) {  
    53.         this.score = score;  
    54.     }  
    55.       
    56.       
    57. }  
    58.   
    59. public class T {  
    60.     public static void main(String[] args) throws Exception{  
    61.         Student stu[] = {new Student("张三",22,80f)  
    62.                         ,new Student("李四",23,83f)  
    63.                         ,new Student("王五",21,80f)};  
    64.           
    65.         Arrays.sort(stu);   //进行排序操作  
    66.         for (int i = 0; i < stu.length; i++) {  
    67.             Student s = stu[i];  
    68.             System.out.println(s);  
    69.         }  
    70.     }  
    71. }  


    分析比较器的排序原理

    实际上比较器的操作,就是经常听到的二叉树的排序算法。

    排序的基本原理:使用第一个元素作为根节点,之后如果后面的内容比根节点小,则放在左子树,如果内容比根节点的内容要大,则放在右子树。

    1. package com.itmyhome;  
    2.   
    3. class BinaryTree {  
    4.     class Node { // 声明一个节点类  
    5.         private Comparable data; // 保存具体的内容  
    6.         private Node left; // 保存左子树  
    7.         private Node right; // 保存右子树  
    8.   
    9.         public Node(Comparable data) {  
    10.             this.data = data;  
    11.         }  
    12.   
    13.         public void addNode(Node newNode) {  
    14.             // 确定是放在左子树还是右子树  
    15.             if (newNode.data.compareTo(this.data) < 0) { // 内容小,放在左子树  
    16.                 if (this.left == null) {  
    17.                     this.left = newNode; // 直接将新的节点设置成左子树  
    18.                 } else {  
    19.                     this.left.addNode(newNode); // 继续向下判断  
    20.                 }  
    21.             }  
    22.             if (newNode.data.compareTo(this.data) >= 0) { // 放在右子树  
    23.                 if (this.right == null) {  
    24.                     this.right = newNode; // 没有右子树则将此节点设置成右子树  
    25.                 } else {  
    26.                     this.right.addNode(newNode); // 继续向下判断  
    27.                 }  
    28.             }  
    29.         }  
    30.   
    31.         public void printNode() { // 输出的时候采用中序遍历  
    32.             if (this.left != null) {  
    33.                 this.left.printNode(); // 输出左子树  
    34.             }  
    35.             System.out.print(this.data + " ");  
    36.             if (this.right != null) {  
    37.                 this.right.printNode();  
    38.             }  
    39.         }  
    40.     };  
    41.   
    42.     private Node root; // 根元素  
    43.   
    44.     public void add(Comparable data) { // 加入元素  
    45.         Node newNode = new Node(data); // 定义新的节点  
    46.         if (root == null) { // 没有根节点  
    47.             root = newNode; // 第一个元素作为根节点  
    48.         } else {  
    49.             root.addNode(newNode); // 确定是放在左子树还是放在右子树  
    50.         }  
    51.     }  
    52.   
    53.     public void print() {  
    54.         this.root.printNode(); // 通过根节点输出  
    55.     }  
    56. };  
    57.   
    58. public class T2 {  
    59.     public static void main(String args[]) {  
    60.         BinaryTree bt = new BinaryTree();  
    61.         bt.add(8);  
    62.         bt.add(3);  
    63.         bt.add(3);  
    64.         bt.add(10);  
    65.         bt.add(9);  
    66.         bt.add(1);  
    67.         bt.add(5);  
    68.         bt.add(5);  
    69.         System.out.println("排序之后的结果:");  
    70.         bt.print();  
    71.     }  
    72. };  


     

    另一种比较器:Compartor

    如果一个类已经开放完成,但是在此类建立的初期并没有实现Comparable接口,此时肯定是无法进行对象排序操作的,所以为了解决这一的问题,java又定义了另一个比较器的操作接口 Comparator 此接口定义在java.util包中,接口定义如下:

    public  interface  Comparator<T>{

                     public  int  compare(T o1,T o2);

                     boolean  equals(Object  obj);

    }

    MyComparator.java

    1. package com.itmyhome;  
    2.   
    3. import java.util.Comparator;  
    4.   
    5. public class MyComparator implements Comparator<Student> {  //实现比较器  
    6.   
    7.     @Override  
    8.     public int compare(Student stu1, Student stu2) {  
    9.         // TODO Auto-generated method stub  
    10.         if(stu1.getAge()>stu2.getAge()){  
    11.             return 1;  
    12.         }else if(stu1.getAge()<stu2.getAge()){  
    13.             return -1;  
    14.         }else{  
    15.             return 0;  
    16.         }  
    17.     }  
    18.   
    19. }  


     

    1. package com.itmyhome;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.Arrays;  
    5. import java.util.Collections;  
    6. import java.util.List;  
    7.   
    8. class Student {  
    9.     private String name;  
    10.     private int age;  
    11.       
    12.     public Student(String name,int age ){  
    13.         this.name = name;  
    14.         this.age = age;  
    15.     }  
    16.       
    17.     public String toString(){  
    18.         return "姓名:"+this.name+", 年龄:"+this.age;  
    19.     }  
    20.       
    21.     public String getName() {  
    22.         return name;  
    23.     }  
    24.     public void setName(String name) {  
    25.         this.name = name;  
    26.     }  
    27.     public int getAge() {  
    28.         return age;  
    29.     }  
    30.     public void setAge(int age) {  
    31.         this.age = age;  
    32.     }  
    33. }  
    34.   
    35. public class T {  
    36.     public static void main(String[] args) throws Exception{  
    37.         Student stu[] = {new Student("张三",23)  
    38.                         ,new Student("李四",26)  
    39.                         ,new Student("王五",22)};  
    40.         Arrays.sort(stu,new MyComparator());             //对象数组进行排序操作  
    41.           
    42.         List<Student> list = new ArrayList<Student>();  
    43.         list.add(new Student("zhangsan",31));  
    44.         list.add(new Student("lisi",30));  
    45.         list.add(new Student("wangwu",35));  
    46.         Collections.sort(list,new MyComparator());      //List集合进行排序操作  
    47.           
    48.         for (int i = 0; i < stu.length; i++) {  
    49.             Student s = stu[i];  
    50.             System.out.println(s);  
    51.         }  
    52.           
    53.         System.out.println("*********");  
    54.           
    55.         for (int i=0;i<list.size();i++){  
    56.             Student s = list.get(i);  
    57.             System.out.println(s);  
    58.         }  
    59.     }  
    60. }  
  • 相关阅读:
    《构建之法阅读笔记02》
    《人月神话阅读笔记01》
    第四周学习进度条
    子数组2
    敏捷开发方法综述
    子数组1
    第三周学习进度条
    四则运算3
    第二周学习进度条
    四则运算4
  • 原文地址:https://www.cnblogs.com/timssd/p/4790452.html
Copyright © 2020-2023  润新知