A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 塞肥肥塞牙人 中级黑马   /  2014-9-6 22:07  /  1591 人查看  /  8 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Comparable接口的作用

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


Comparable接口

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

Comparable接口的定义如下:

public  interface  Comparable<T>{

        public  int compareTo(T  o);

}

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

1:表示大于

-1:表示小于

0:表示相等


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

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

分析比较器的排序原理

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

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

  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 + "\t");  
  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. };  
复制代码


评分

参与人数 1技术分 +1 收起 理由
格子、 + 1 赞一个!

查看全部评分

8 个回复

倒序浏览

另一种比较器:Compartor

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

public  interface  Comparator<T>{

                 public  int  compare(T o1,T o2);

                 boolean  equals(Object  obj);

}

MyComparator.java

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



回复 使用道具 举报
写的很详细
回复 使用道具 举报
感谢楼主分享!
回复 使用道具 举报
很详细,赞一个。
回复 使用道具 举报
谢谢分享。。
回复 使用道具 举报
干雪分享,学习了
回复 使用道具 举报
感谢楼主分享!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马