黑馬程式員_<<Set,TreeSet>>

來源:互聯網
上載者:User


1.TreeSet 1.     概述

    

2.     自然定序(Comparable)

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:25zhangsan:22zhangsan: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)

 

 

當比較子和自訂的自然排序同時存在的時候,那麼就一比較子為主。


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:23java03:22net03:25net07: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());   }} }結果:aadcdfabcdabcdfrr  

ASP.Net+Android+IOS開發.Net培訓

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.