黑馬程序員_

--------------------ASP.Net+Android+IOS開發.Net培訓、期待與您交流! --------------------


1.TreeSet

1.     概述

     TreeSet本身對元素記性排序,要是自定的類,那麼要是此類對象存數TreeSet中,那麼就必須是S自定義的類本身具備比較性,那麼據必須實現接口Comparable,並重寫方法compareTo()方法,底層數據結構是二叉樹

compareTo()返回值是整數,如果小於0,那麼此對象就小於比較的對象,等於0,那麼此對象就等於比較的對象,如果大於0,那麼此對象就大於比較的對象。

2.     自然排序規則(Comparable)

有的對象在存儲到TreeSet本身就具備可比性,例如:String類,是要找ASCII大小比較的,那麼我們就以自定義的類來存儲TreeSet中,使其具備可比性。


package www.fuxi.jihe;
//自定義的異常
public class RunntimeNoStudentExceptionextends RuntimeException {
    publicRunntimeNoStudentException(String message){
      super(message);
    }
}
 
package www.fuxi.jihe;
 
public class Student implements Comparable {
   private String name;// 姓名
   private int age;// 年齡
  
   public Student(Stringname, int age) {
     super();
     this.name = name;
     this.age = age;
   }
 
   public String getName() {
     return name;
   }
 
   public int getAge() {
     return age;
   }
 
   public int compareTo(Object o) {
     if(!(o instanceof Student))
        throw new RunntimeNoStudentException("不是Student對象");
     Student stu=(Student)o;
     if(this.name.equals(stu.name)){
        return this.age-stu.age;
     }
     return this.name.compareTo(stu.name);
   }
 
}
package www.fuxi.jihe;
 
import java.util.Iterator;
import java.util.TreeSet;
 
public class TreeSetDemo {
   public static void main(String[]args) {
     TreeSet set=new TreeSet();
     set.add(new Student("zhangsan",22));
     set.add(new Student("zhangsan",23));
     set.add(new Student("zhangsan",22));
     set.add(new Student("lisi",25));
     Iterator it=set.iterator();
     while(it.hasNext()){
        Student stu=(Student)it.next();
        System.out.println(stu.getName()+":"+stu.getAge());
     }
   }
 
}
 
結果:
lisi:25
zhangsan:22
zhangsan:23
 


從結果可以看出,如果名字相同,則比較年齡,如果年齡也相同,那麼對象就相同了,此不存入此對象。

 

3.     模擬二叉樹

 

 

package www.fuxi.jihe;
 
class ErChaShu {
   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) {// 利用compareTo方法比較
          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 = null;// 存放根節點
 
   public void add(Comparable com) {// 加入新元素
     Node newNode = new Node(com);// 定義新結點
     if (this.root == null) {
        this.root = newNode;
     } else {
        this.root.addNode(newNode);// 判斷是放在左子樹還是右子樹
     }
   }
 
   public void print() {// 輸出新結點
     this.root.printNode();
   }
}
 
public class TextClass {
   public static void main(String[] agrs) throws Exception {
     ErChaShu t = new ErChaShu();
     t.add(4);// 添加元素
     t.add(2);
     t.add(0);
     t.add(7);
     t.add(9);
     t.add(8);
     t.print();// 輸出元素
   }
}
 
結果:
0  2  4  7  8  9 


4.     自定義比較器(Comparator)

  除了第一種比較方式,自然的排序,是對象本身具備比較性,還有另一種比較方式,那就是使集合具備比較性,那就是自定義比較器,把比較器通過構造方式傳給集合,使集合劇本比較性。

 

步驟:定義一個類,實現接口Comparator,然後重寫方法compare方法。

 

當比較器和自定義的自然排序同時存在的時候,那麼就一比較器爲主。


public class RunntimeNoStudentException extends RuntimeException {
    publicRunntimeNoStudentException(String message){
      super(message);
    }
}
public class Person {
   private String name;// 姓名
   private int age;// 年齡
 
   public Person(String name, int age) {
     super();
     this.name = name;
     this.age = age;
   }
 
   public String getName() {
     return name;
   }
 
   public int getAge() {
     return age;
   }
 
  
}
import java.util.Comparator;
 
public class MyCompartor implements Comparator {
 
   public int compare(Object o1, Object o2) {//從寫此方法
     if(!(o1 instanceof Person || o2 instanceof Person)){
         throw newRunntimeNoStudentException("不是Person對象");
     }
     Person p=(Person)o1;
     Person p1=(Person)o2;
     int num=p.getName().compareTo(p1.getName());
     if(num==0)
        return p.getAge()-p1.getAge();
     return num;
   }
 
}
package www.fuxi.jihe;
 
import java.util.Iterator;
import java.util.TreeSet;
 
public class TreeSetDemo {
   publicstatic void main(String[] args) {
    
     TreeSetset = new TreeSet(new MyCompartor());
     set.add(newPerson("java03", 22));
     set.add(newPerson("java01", 23));
     set.add(newPerson("net07", 22));
     set.add(newPerson("net03", 25));
     Iteratorit = set.iterator();
     while(it.hasNext()) {
        Personstu = (Person) it.next();
        System.out.println(stu.getName()+ ":" + stu.getAge());
     }
   }
 
}
結果:
java01:23
java03:22
net03:25
net07:22
 


從結果可以看出,先是按照名字排序,然後按照年齡排序。

 

5. 練習

自定義比較器,存儲字符串,字符串按照長度大小排序

 

import java.util.Comparator;
 
public class MyStringCompartor implements Comparator {
 
  public int compare(Object o1, Object o2) {//從寫此方法
    if(!(o1 instanceof String|| o2 instanceof String)){
       throw newRunntimeNoStudentException("不是String的子類或者Person對象");
    }
    Strings1=(String)o1;
    Strings2=(String)o2;
    return s1.length()-s2.length();
  }
 
}
importjava.util.Iterator;
importjava.util.TreeSet;
 
publicclass TreeSetDemo {
public static void main(String[] args) {
  
   TreeSet set = new TreeSet(new MyStringCompartor());
   set.add("abcd");
   set.add("ad");
   set.add("cdf");
   set.add("a");
   set.add("abcdfrr");
   Iterator it = set.iterator();
   while (it.hasNext()) {
     System.out.println(it.next());
   }
}
 
}
結果:
a
ad
cdf
abcd
abcdfrr
 
 

--------------------ASP.Net+Android+IOS開發.Net培訓、期待與您交流! --------------------

發佈了46 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章