集合的API?是不是就是包啊?

解决方案 »

  1.   

    星羅棋佈
    對程式設計來說,collection 是一個很基本的觀念。程式中常常會需要追蹤許多相關的物件(比方說:一群員工或一堆影像)。最基本支援這個概念的當然是陣列,但是 陣列在許多方面卻很棘手,特別是對於會在執行過程中變動個數的 collection 來說,陣列就相當不適合。早在 JDK 1.0 的時代,就已經提供兩個好用的類別來存放 collection ,分別是 java.util.Vector (動態的陣列)和 java.util.Hashtable ( key 和值的組合)。在這方面, Java 2 提供了更完全的方法,稱之為 Collections Framework。Java 2 中一樣有 Vector 和 Hashtable ,但他們已經被納入 Collections Framework 中。在本月的專欄中,我會介紹 Collections Framework ,並告訴你它能做些什麼。Collections Framework 的架構
    java.util package 中的介面( interface )是 Collections Framework 的根基所在。這些介面被分成兩大類:第一類繼承自 Collection 介面。 Collection (及其繼承者)用來當作許多其它物件的容器;第二類繼承自 Map 介面,可以透過 key 來索引到 collection 內的值。Collection 介面
    所有的 collection 都繼承自 Collection 介面。 Collection 就像是一個盒子,可以容納許多其它物件,這些內容物件是否可以重複,或是否有次序,都未在 Collection 中明確定義,而由其子介面定義。不過, Collection 介面倒是定義了一些基本操作:public boolean add ( Object o )將物件加入此 collection 中。如果成功,傳出值是 true 。如果物件已經存在而且此 collection 型態不允許物件重複加入,那麼就傳回 false 。如果此 collection 型態是唯讀的,呼叫此 method 將會導致 UnsupportedOperationException 例外。public boolean remove ( Object o )移除物件。如果成功,傳出值是 true 。如果物件不存在此集合中,則傳出 false 。如果此 collection 型態是唯讀的,呼叫此 method 將會導致 UnsupportedOperationException 例外。public boolean contains ( Object o )如果此物件存在此集合中,則傳出 true 。public int size()取得 collection 內的元素個數。public boolean isEmpty()如果 collection 是空的,傳出值是 true 。public Iterator iterator()此 method 傳出一個 Iterator 物件,透過此 Iterator 物件可以一個一個地「走訪」 collection 內所有的元素。下一節對 Iterator 有更詳細的說明。為了方便,你可以透過下面的 method 來將此集合轉成陣列:public Object[] toArray()public Object[] toArray(Object[] a)此二 method 傳出一個 collection 元素所形成的陣列。第二個 method 傳出的陣列型態同 a 物件。請注意,上述這些 methods 都是每個 Collection 的子類別必須實作的。什麼 Iterator?Enumerator?我的天呀!
    究竟 java.util.Iterator 介面是做什麼的?它本質上是一種 Enumeration 。你可能還記得在 JDK 1.0 和 JDK 1.1 中, Enumeration 是用來讓你一一造訪所有元素的一種工具。public Object next()傳出此 iterator 的下一個元素。public boolean hasNext()如果你還未一一造訪完所有的元素,則傳出 true 。換句話說,如果呼叫 next()可以正常取得元素的話,傳出 true。此二 method 就如同 Enumeration 的 nextElement() 和 hasMoreElements() 一般。下面的範例展示如何使用 Iterator 來印出 collection 內的每一個元素。  public void printElements(Collection c, PrintStream out) {
        Iterator iterator = c.iterator();
        while (iterator.hasNext())
          out.println(iterator.next());
      }
    Iterator 也可以用來移除 collection 內的元素:public void remove()移走此 iterator 的 collection 的下一個物件(也就是 next() 傳出的物件)。並非所有的 iterator 都有實作此 method ,比方說,唯讀的 collection 就不需要實作此 method 。如果不允許使用 remove() 的話,那麼 remove() 就應該傳出 UnsupportedOperationException 例外。如果你一開始尚未透過 next() 來指到初始位置就先呼叫 remove() ,或者是連續呼叫 remove() 兩次,就會收到 IllegalStateException 例外。Collection 的種類
    Collection 介面有兩個子介面: Set 介面不允許重複的元素; List 介面的元素必須有特定編號次序。 Set 介面還有一個子介面叫做 SortedSet ,其元素都必須維持在排序狀態(關於排序,稍後再詳談)。除了那些繼承自 Collection 的 method 之外, Set 沒有其它的 method 。另外, Set 強制規定不允許重複的元素,如果意圖加入重複的元素,那麼 add() method會傳出 false 。SortedSet 比 Set 多了幾個 method 。不管你用 add() 或 remove(),SortedSet 一定都會保持順序。利用 subSet()、headSet()、以及 tailSet() ,你可以取出一個也是有序的子集合。利用 first()、last()、以及 comparator(),你分別可以取得第一個元素、最後一個元素,以及用來比較元素的物件(稍後再詳述)。另一個 Set 的子介面是 List,List 介面有能力處理特定位置的元素。public void add(int index, Object element)將物件放到特定位置。如果位置小於 0 或大於總個數,就會收到 IndexOutOfBoundsException 例外。原位置以及其後的物件會向後順移一個位置。public void remove(int index)移走特定位置的物件,所有後續的物件向前遞移一格。public void get(int index)取得特定位置的物件。public void set(int index, Object element)將特定位置的物件用另一個物件取代。List 還有一些其它的 method ,但是礙於篇幅,我不打算在此說明。後面的小節中,我會介紹有哪些類別實作了這些 collection 介面。Map 介面
    Collections Framework 也包含了 Map 的概念, Map 內的每個元素都有 key 和值兩部分。 Map 的基本使用方式很直覺(如果你記得 Hashtable 類別的話,你會覺得 Map 很類似):public Object put(Object key, Object value)加入一組 key 和值。如果此 map 中已經有一個相同的 key ,那麼對應的舊值會被取代。public Object get(Object key)取得特定 key 所對應的值。public Object remove(Object key)移除特定 key 所對應的值。public int size()取得元素個數。你可以透過下面的兩種方式來取出所有的元素:public Set keySet()將 map 內所有的 key 集中在一個 Set 物件中,然後傳出此 set 。這裡選用 Set 當作傳出型態,是因為 key 不能重複。public Collection values()傳出 map 內所有值的集合。值是可以重複的。SortedMap 是 Map 的子介面,SortedMap 將值依照 key 的次序來排列,它提供了 subMap()、headMap()、以及 tailMap() 來取出排列妥的 map 子集合。如同 SortedSet 一般,SortedMap 也提供了 comparator(),可以用來取得排序時比較用的物件,稍後有更詳說明。實作的類別
    在此之前,我談的都是介面,但介面是不能直接被實體化的。 Collections Framework 包含了一些有用的類別,它們實作了這些介面,如下表所列:介面 實作 
    Set HashSet 
    SortedSet TreeSet 
    List ArrayList, LinkedList, Vector 
    Map HashMap, Hashtable 
    SortedMap TreeMap 如果你常常需要在 list 尾端加入元素的話,你應該用 ArrayList ,因為它的效率比較好(不過,如果你常常需要插入或刪除元素的話, LinkedList 的效率比較好)。Vector 依然和 JDK 1.0 時代的 Vector 一樣,只是多實作了 List 介面的 method。Vector 的 method 享有同步化(synchronize)所帶來的好處,多個執行緒 可以同時存取 Vector。舊的 Hashtable 也做了更新,新的 Hashtable 實作了 Map 介面,也享有同步化所帶來的好處。等一下你將會看到,想取得同步化的 collection ,有一些更一般化的方法。Slam Dunking with Collections
    java.util.Collections 類別有許多靜態的 method ,可以用在 Set 和 Map 上(請注意,別混淆了 java.util.Collections 類別和 java.util.Collection 介面)。因為 Collections 類別所提供的靜態 method 都是以介面為參數型態,所以只要實作了這些介面,任何類別都可以使用這些 method ,這麼一來,威力可真是不同凡響。我們能利用 Collections 類別的 method 來做些什麼呢?你可以利用下面的 method ,來建立任何 collection 的同步化版本:public static Collection synchronizedCollection(Collection c)public static Set synchronizedSet(Set s)public static List synchronizedList(List list)public static Map synchronizedMap(Map m)public static SortedSet synchronizedSortedSet(SortedSet s)public static SortedMap synchronizedSortedMap(SortedMap m)這些 method 用來建立支援同步化且可以使用多執行緒的 collection 。如果你會讓多個執行緒同時存取到 collection ,那麼你會發現這些 method 很好用。如果你想知道更進一步的資料,請自行參閱 Collections 的說明文件。甚至,你還可以使用 Collections 類別來建立任何 collection 的唯讀版本:public static Collection unmodifiableCollection(Collection c)public static Set unmodifiableSet(Set s)public static List unmodifiableList(List list)public static Map unmodifiableMap(Map m)public static SortedSet unmodifiableSortedSet(SortedSet s)public static SortedMap unmodifiableSortedMap(SortedMap m)建立唯讀的 collection 物件。輕輕鬆鬆地排序
    Collections 還包含其它的 method,用來進行一般的操作,像是排序。排序的 method 有兩個:public static void sort(List list)將傳進來的串列參數排序,此串列的元素必須實作 java.lang.Comparable 介面才行。還好,許多類別都有實作 Comparable,這些類別包括 String、Date、BigInteger、以及 基本型態的包裝類別(Integer、Double 等等)。public static void sort(List list, Comparator c)用來排序元素沒實作 Comparable 的 List,第二個參數用來擔任比較大小的工作。比方說,你可能寫一個 ImaginaryNumber 類別,然後你希望此類別的 List 也能排序。你可以設計一個實作 Comparator 介面的類別,讓此類別來比較 ImaginaryNumber。Collections 還有一些其它的功能,如果你感興趣的話,請自行查詢 min()、max()、binarySearch()、和 reverse() 的用法。範例
    collections 是一個「家常便飯」的主題,實在難以設計出令人興奮的範例。下面的範例程式用來讀取文字檔、剖析文字、計算出現頻率、排序、並將結果寫到另一個檔案。透過此範例,你應該 就能體會要如何使用 collection:import java.io.*;
    import java.util.*;public class WordSort {
      public static void main(String[] args) throws IOException {
        // Get the command-line arguments.
        if (args.length < 2) {
          System.out.println("Usage: WordSort inputfile outputfile");
          return;
        }
        String inputfile = args[0];
        String outputfile = args[1];
           // Create the word map. Each key is a word
        //   and each value is an Integer that represents
        //   the number of times the word occurs in the
        //   input file.
        Map map = new HashMap();
           // Read every line of the input file.
        BufferedReader in = new BufferedReader(new FileReader(inputfile));
        String line;
        while ((line = in.readLine()) != null) {
          // Examine each word on the line.
          StringTokenizer st = new StringTokenizer(line);
          while (st.hasMoreTokens()) {
            String word = st.nextToken();
            Object o = map.get(word);
            // If there's no entry for this word, add one.
            if (o == null) map.put(word, new Integer(1));
            // Otherwise, increment the count for this word.
            else {
              Integer count = (Integer)o;
              map.put(word, new Integer(count.intValue() + 1));
            }
          }
        }
        in.close();
           // Get the map's keys and sort them.
        List keys = new ArrayList(map.keySet());
        Collections.sort(keys);    // Now write the results to the output file.
        PrintWriter out = new PrintWriter(new FileWriter(outputfile));
        Iterator iterator = keys.iterator();
        while (iterator.hasNext()) {
          Object key = iterator.next();
          out.println(key + " : " + map.get(key));
        }
        out.close();
      }
    }如果輸入檔 Ian Moore.txt 的內容如下:    Well it was my love that kept you going
        Kept you strong enough to fall
        And it was my heart you were breaking
        When he hurt your pride
        So how does it feel
        How does it feel
        How does it feel
        How does it feel你可以用下面的方式來執行:    java WordSort "Ian Moore.txt" count.txt執行完後的結果存在 count.txt 檔中,內容如下:    And : 1
        How : 3
        Kept : 1
        So : 1
        Well : 1
        When : 1
        breaking : 1
        does : 4
        enough : 1
        fall : 1
        feel : 4
        going : 1
        he : 1
        heart : 1
        how : 1
        hurt : 1
        It : 6
        kept : 1
        love : 1
        my : 2
        pride : 1
        strong : 1
        that : 1
        to : 1
        was : 2
        were : 1
        you : 3
        your : 1public void printElements(Collection c, PrintStream out) {Iterator iterator = c.iterator();while (iterator.hasNext())out.println(iterator.next());}本程式將大小寫視為不同,所以「How」和「how」被視為不同的字。你可以修改這點,在 StringTokenizer 處理完後將其轉成小寫即可:String word = st.nextToken().toLowerCase();更進一步的資料
    現在你大概已經瞭解 Collections Framework ,也知道其資料結構和用法。如果你想取得更多細節,請造訪下面的網頁:http://java.sun.com/docs/books/tutorial/collections/index.htmlSun 的教學資料相當豐富,如果你想更進一步瞭解 Collections Framework ,建議讀者來此看看。http://www.javaworld.com/javaworld/jw-01-1999/jw-01-jglvscoll.html這篇 JavaWorld 的文章是由 Laurence Vanhelsuwe 所寫,它詳細地比較了 Collections Framework 和 JGL 的異同( JGL 是一套由 ObjectSpace 公司所設計的 collection 程式庫)。雖然文章的結論中也認為比較此二程式庫猶如比較蘋果和橘子一般地不恰當,但本文章仍有一些不錯的見解。如果你已經熟悉了JGL,本文章對學習 Collections Framework 有幫助。
      

  2.   

    同样在SL275里,这句怎么翻译?
    Supports dynamically changing programs during
    runtime by loading classes from disparate sources