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
          主站蜘蛛池模板: 长宁区| 江孜县| 焦作市| 赞皇县| 开江县| 新龙县| 阿勒泰市| 铜梁县| 育儿| 南靖县| 和硕县| 靖宇县| 澄江县| 油尖旺区| 黄山市| 日照市| 衡山县| 龙门县| 宁化县| 北流市| 濉溪县| 大石桥市| 高雄市| 万源市| 余姚市| 油尖旺区| 丹巴县| 呼伦贝尔市| 广灵县| 美姑县| 沁水县| 红原县| 鹿泉市| 永安市| 绿春县| 咸阳市| 额敏县| 井陉县| 正镶白旗| 临泉县| 龙井市|