【Java常用類庫】_比較子(Comparable、Comparator)筆記

來源:互聯網
上載者:User

【Java常用類庫】_比較子(Comparable、Comparator)筆記

本章目標:
掌握Comparable比較介面的使用
瞭解比較子的基本排序原理
掌握Comparator比較介面的使用

Comparable介面

可以直接使用java.util.Arrays類進行數組的排序操作,但對象所在的類必須實現Comparable介面,用於指定排序介面。

Comparable介面定義類如下:

public interface Comparable<T>{
    public int compareTo(T o);
}
此方法返回一個int類型的資料,但是此int的值只能是以下三種:

1:表示大於
-1:表示小於
0:表示相等

執行個體代碼:

class Student implements Comparable<Student>{    private String name;    private int age;    private float score;    public Student(String name,int age,float score){        this.name = name;        this.age = age;        this.score = score;    }    public String toString(){        return name+"\t\t"+this.age+"\t\t"+this.score;    }    public int compareTo(Student stu){        if(this.score>stu.score){            return -1;        }else if(this.score<stu.score){            return 1;        }else{            if(this.age>stu.age){                return 1;            }else if(this.age<stu.age){                return -1;            }else{                return 0;            }        }    }}public class ComparableDemo01{    public static void main(String args[]){        Student stu[] = {new Student("張三",20,99.0f),new Student("李四",22,90.0f),new Student("王五",22,100.0f)};        java.util.Arrays.sort(stu);    //進行排序操作        for(int i=0;i<stu.length;i++){    //迴圈輸出數組內容            System.out.println(stu[i]);        }    }}

注意:如果在此時Student類中沒有實現Comparable介面,則在執行時會出現以下的異常。

Exception in thread "main" java.lang.ClassCastException:

3.2、分析比較子的排序原理:

實際上之前所講解的排序過程,也就是經常聽到資料結構中的二叉樹的排序方法,通過二叉樹進行排序,之後利用中序遍曆的方式把內容依次讀取出來。

中序遍曆首先遍曆左子樹,然後訪問根結點,最後遍曆右子樹。在遍曆左、右子樹時,仍然先遍曆左子樹,再訪問根結點,最後遍曆右子樹。


下面就自己手工實現一個二叉樹的比較演算法。
為了操作方法,此處使用Integer類完成。

public class ComparableDemo02{    public static void main(String args[]){        Comparable com = null ;            // 聲明一個Comparable介面對象        com = 30 ;                        // 通過Integer為Comparable執行個體化        System.out.println("內容為:" + com) ;    // 調用的是toString()方法    }};

瞭解了此特性之後,下面就可以動手完成一個二叉樹演算法。

class BinaryTree{    class Node{            // 聲明一個節點類        private Comparable data ;    // 儲存具體的內容        private Node left ;            // 儲存左子樹        private Node right ;        // 儲存右子樹        public Node(Comparable data){            this.data = data ;        }        public void addNode(Node newNode){            // 確定是放在左子樹還是右子樹            if(newNode.data.compareTo(this.data)<0){    // 內容小,放在左子樹                if(this.left==null){                    this.left = newNode ;    // 直接將新的節點設定成左子樹                }else{                    this.left.addNode(newNode) ;    // 繼續向下判斷                }            }            if(newNode.data.compareTo(this.data)>=0){    // 放在右子樹                if(this.right==null){                    this.right = newNode ;    // 沒有右子樹則將此節點設定成右子樹                }else{                    this.right.addNode(newNode) ;    // 繼續向下判斷                }            }        }        public void printNode(){    // 輸出的時候採用中序遍曆            if(this.left!=null){                this.left.printNode() ;    // 輸出左子樹            }            System.out.print(this.data + "\t") ;            if(this.right!=null){                this.right.printNode() ;            }        }    };    private Node root ;        // 根項目    public void add(Comparable data){    // 加入元素        Node newNode = new Node(data) ;    // 定義新的節點        if(root==null){    // 沒有根節點            root = newNode ;    // 第一個元素作為根節點        }else{            root.addNode(newNode) ; // 確定是放在左子樹還是放在右子樹        }    }    public void print(){        this.root.printNode() ;    // 通過根節點輸出    }};public class ComparableDemo03{    public static void main(String args[]){        BinaryTree bt = new BinaryTree() ;        bt.add(8) ;        bt.add(3) ;        bt.add(3) ;        bt.add(10) ;        bt.add(9) ;        bt.add(1) ;        bt.add(5) ;        bt.add(5) ;        System.out.println("排序之後的結果:") ;        bt.print() ;    }};

3.3、另一種比較子:Comparator

直接貼出代碼:

import java.util.* ;class Student{    // 指定類型為Student    private String name ;    private int age ;    public Student(String name,int age){        this.name = name ;        this.age = age ;    }    public boolean equals(Object obj){    // 覆寫equals方法        if(this==obj){            return true ;        }        if(!(obj instanceof Student)){            return false ;        }        Student stu = (Student) obj ;        if(stu.name.equals(this.name)&&stu.age==this.age){            return true ;        }else{            return false ;        }    }    public void setName(String name){        this.name = name ;    }    public void setAge(int age){        this.age = age ;    }    public String getName(){        return this.name ;    }    public int getAge(){        return this.age ;    }    public String toString(){        return name + "\t\t" + this.age  ;    }};class StudentComparator implements Comparator<Student>{    // 實現比較子    // 因為Object類中本身已經有了equals()方法    public int compare(Student s1,Student s2){        if(s1.equals(s2)){            return 0 ;        }else if(s1.getAge()<s2.getAge()){    // 按年齡比較            return 1 ;        }else{            return -1 ;        }    }};public class ComparatorDemo{    public static void main(String args[]){        Student stu[] = {new Student("張三",20),            new Student("李四",22),new Student("王五",20),            new Student("趙六",20),new Student("孫七",22)} ;        java.util.Arrays.sort(stu,new StudentComparator()) ;    // 進行排序操作        for(int i=0;i<stu.length;i++){    // 迴圈輸出數組中的內容            System.out.println(stu[i]) ;        }    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.