AntSoul

          它總是在行走,行走,永遠的行走…… 行走是它生存的恒久姿態和最佳造型。 它似乎有一雙不知疲倦的腳。 ———我說的是螞蟻。

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            42 隨筆 :: 0 文章 :: 1 評論 :: 0 Trackbacks

          ┳ TreeSet (實現了SortedSet接口的類)
          1.? TreeSet是依靠TreeMap來實現的。
          2.? TreeSet是一個有序集合,TreeSet中的元素按照升序排列,缺省是按照自然排序,一位著TreeSet要實現Comparable接口。
          3.? 可以在構造TreeSet對象時,傳遞實現了Comparable接口的比較器對象。
          demo

          import java.util.*;

          class TreeSetTest
          {
          ?public static void main(String[] args){
          ?? TreeSet ts = new TreeSet();
          ??
          ?? ts.add(new Student("one",1));
          ?? ts.add(new Student("two",4));
          ?? ts.add(new Student("three",3));
          ??
          ?? Iterator it = ts.iterator();
          ?? while(it.hasNext()){
          ?? ?System.out.println(it.next());
          ??}
          ?}
          }

          class Student implements Comparable
          {
          ?private String name;
          ?private int num;
          ?
          ?//為了調用方便聲明為static
          ?static class StudentComparator implements Comparator
          ?{
          ?? public int compare(Object o1,Object o2){
          ??? Student s1 =(Student)o1;
          ??? Student s2 =(Student)o2;
          ??? int result;
          ???
          ??? result = s1.num > s2.num ? 1 :(s1.num==s2.num ? 0 : -1);
          ??? if(result == 0){ //student的num相同,比較name,因為name為String類型,它實現了Comparable<String>
          ??? ? result = s1.name.compareTo(s2.name);
          ??? }
          ??? return result;
          ?? }?
          ?}
          ?
          ?public Student(String name,int num){
          ??this.name = name;
          ??this.num = num;
          ?}
          ?
          ?public int compareTo(Object o){
          ??Student s =(Student)o;
          ??return num > s.num ? 1 : (num == s.num ? 0 : -1);
          ?}
          ?
          ?public String toString(){
          ??return "num="+num+" "+"name="+name;
          ?}
          }

          posted on 2007-03-10 18:02 yok 閱讀(160) 評論(0)  編輯  收藏 所屬分類: CoreJava
          主站蜘蛛池模板: 上杭县| 海安县| 庐江县| 故城县| 龙口市| 大关县| 卫辉市| 鸡东县| 桂林市| 兴海县| 吉安市| 武义县| 垦利县| 宜阳县| 仲巴县| 砚山县| 上林县| 项城市| 长泰县| 青田县| 金华市| 宣武区| 南郑县| 临澧县| 北票市| 安顺市| 桑植县| 东至县| 罗甸县| 建瓯市| 阿勒泰市| 锦屏县| 庆安县| 马尔康县| 东乌珠穆沁旗| 台东市| 曲水县| 喀喇| 木里| 杭锦旗| 化德县|