程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Collections類中的實用工具

Collections類中的實用工具

編輯:關於JAVA

Collections類中含有其他大量有用的實用工具(如表二):

enumeration(Collection) 為自變量產生原始風格的Enumeration(枚舉)
max(Collection),min(Collection) 在自變量中用集合內對象的自然比較方法產生最大或最小元素
max(Collection,Comparator),min(Collection,Comparator) 在集合內用比較器產生最大或最小元素
nCopies(int n, Object o) 返回長度為n的一個不可變列表,它的所有句柄均指向o
subList(List,int min,int max) 返回由指定參數列表後推得到的一個新列表。可將這個列表想象成一個“窗口”,它自索引為min的地方開始,正好結束於max的前面

enumeration(Collection)
 

Produces an old-style Enumeration for the argument.
 

max(Collection)
 

min(Collection)
 

Produces the maximum or minimum element in the argument using the natural comparison method of the objects in the Collection.
 

max(Collection, Comparator)
 

min(Collection, Comparator)
 

Produces the maximum or minimum element in the Collection using the Comparator.
 

nCopies(int n, Object o)
 

Returns an immutable List of size n whose handles all point to o.
 

subList(List, int min, int max)
 

Returns a new List backed by the specified argument List that is a window into that argument with indexes starting at min and stopping just before max.
 

表二

注意min()和max()都是隨同Collection對象工作的,而非隨同List,所以不必擔心Collection是否需要排序(就象早先指出的那樣,在執行一次binarySearch()——即二進制搜索——之前,必須對一個List或者一個數組執行sort())。

1. 使Collection或Map不可修改
通常,創建Collection或Map的一個“只讀”版本顯得更有利一些。Collections類允許我們達到這個目標,方法是將原始容器傳遞進入一個方法,並令其傳回一個只讀版本。這個方法共有四種變化形式,分別用於Collection(如果不想把集合當作一種更特殊的類型對待)、List、Set以及Map。下面這個例子演示了為它們分別構建只讀版本的正確方法:
 

//: ReadOnly.java
// Using the Collections.unmodifiable methods
package c08.newcollections;
import java.util.*;

public class ReadOnly {
  public static void main(String[] args) {
    Collection c = new ArrayList();
    Collection1.fill(c); // Insert useful data
    c = Collections.unmodifiableCollection(c);
    Collection1.print(c); // Reading is OK
    //! c.add("one"); // Can't change it
    
    List a = new ArrayList();
    Collection1.fill(a);
    a = Collections.unmodifiableList(a);
    ListIterator lit = a.listIterator();
    System.out.println(lit.next()); // Reading OK
    //! lit.add("one"); // Can't change it

    Set s = new HashSet();
    Collection1.fill(s);
    s = Collections.unmodifiableSet(s);
    Collection1.print(s); // Reading OK
    //! s.add("one"); // Can't change it
    
    Map m = new HashMap();
    Map1.fill(m, Map1.testData1);
    m = Collections.unmodifiableMap(m);
    Map1.print(m); // Reading OK
    //! m.put("Ralph", "Howdy!");
  }
} ///:~

對於每種情況,在將其正式變為只讀以前,都必須用有有效的數據填充容器。一旦載入成功,最佳的做法就是用“不可修改”調用產生的句柄替換現有的句柄。這樣做可有效避免將其變成不可修改後不慎改變其中的內容。在另一方面,該工具也允許我們在一個類中將能夠修改的容器保持為private狀態,並可從一個方法調用中返回指向那個容器的一個只讀句柄。這樣一來,雖然我們可在類裡修改它,但其他任何人都只能讀。
為特定類型調用“不可修改”的方法不會造成編譯期間的檢查,但一旦發生任何變化,對修改特定容器的方法的調用便會產生一個UnsupportedOperationException違例。

2. Collection或Map的同步
synchronized關鍵字是“多線程”機制一個非常重要的部分。我們到第14章才會對這一機制作深入的探討。在這兒,大家只需注意到Collections類提供了對整個容器進行自動同步的一種途徑。它的語法與“不可修改”的方法是類似的:
 

//: Synchronization.java
// Using the Collections.synchronized methods
package c08.newcollections;
import java.util.*;

public class Synchronization {
  public static void main(String[] args) {
    Collection c = 
      Collections.synchronizedCollection(
        new ArrayList());
    List list = Collections.synchronizedList(
      new ArrayList());
    Set s = Collections.synchronizedSet(
      new HashSet());
    Map m = Collections.synchronizedMap(
      new HashMap());
  }
} ///:~


在這種情況下,我們通過適當的“同步”方法直接傳遞新容器;這樣做可避免不慎暴露出未同步的版本。
新集合也提供了能防止多個進程同時修改一個容器內容的機制。若在一個容器裡反復,同時另一些進程介入,並在那個容器中插入、刪除或修改一個對象,便會面臨發生沖突的危險。我們可能已傳遞了那個對象,可能它位位於我們前面,可能容器的大小在我們調用size()後已發生了收縮——我們面臨各種各樣可能的危險。針對這個問題,新的集合庫集成了一套解決的機制,能查出除我們的進程自己需要負責的之外的、對容器的其他任何修改。若探測到有其他方面也准備修改容器,便會立即產生一個ConcurrentModificationException(並發修改違例)。我們將這一機制稱為“立即失敗”——它並不用更復雜的算法在“以後”偵測問題,而是“立即”產生違例。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved