Skip to content

Commit beec799

Browse files
committed
附录:集合主题 翻译更新至 集合工具类
1 parent cdb1605 commit beec799

1 file changed

Lines changed: 314 additions & 0 deletions

File tree

‎docs/book/Appendix-Collection-Topics.md‎

Lines changed: 314 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2512,6 +2512,320 @@ public class LinkedHashMapDemo {
25122512
<!-- Utilities -->
25132513
## 集合工具类
25142514

2515+
集合有许多独立的实用工具程序,在 **java.util.Collections** 中表示为静态方法。之前已经见过其中一些,例如 `addAll()` , `reverseOrder()` 和 `binarySearch()` 。以下是其他内容(同步和不可修改的实用工具程序将在后面的章节中介绍)。在此表中,在需要的时候使用了泛型:
2516+
2517+
| 方法 | 描述 |
2518+
| :--- | :--- |
2519+
| **checkedCollection(Collection\<T> c, Class\<T> type)** <br><br> **checkedList(List\<T> list, Class\<T> type)** <br><br> **checkedMap(Map\<K, V> m, Class\<K> keyType, Class\<V> valueType)** <br><br> **checkedSet(Set\<T> s, Class\<T> type)** <br><br> **checkedSortedMap(SortedMap\<K, V> m, Class\<K> keyType, Class\<V> valueType)** <br><br> **checkedSortedSet(SortedSet\<T> s, Class\<T> type)** | 生成 **Collection** 的动态类型安全视图或 **Collection** 的特定子类型。 当无法使用静态检查版本时使用这个版本。 <br><br> 这些方法的使用在[第九章 多态]()章节的“动态类型安全”标题下进行了展示。 |
2520+
| **max(Collection)** <br><br> **min(Collection)** | 使用 **Collection** 中对象的自然比较方法生成参数集合中的最大或最小元素。 |
2521+
| **max(Collection, Comparator)** <br><br> **min(Collection, Comparator)** | 使用 **Comparator** 指定的比较方法生成参数集合中的最大或最小元素。 |
2522+
| **indexOfSubList(List source, List target)** | 返回 **target** 在 **source** 内第一次出现的起始索引,如果不存在则返回 -1。 |
2523+
| **lastIndexOfSubList(List source, List target)** | 返回 **target** 在 **source** 内最后一次出现的起始索引,如果不存在则返回 -1。 |
2524+
| **replaceAll(List\<T> list, T oldVal, T newVal)** | 用 **newVal** 替换列表中所有的 **oldVal** 。 |
2525+
| **reverse(List)**| 反转列表 |
2526+
| **reverseOrder()** <br><br> **reverseOrder(Comparator\<T>)** | 返回一个 **Comparator** ,它与集合中实现了 **comparable\<T>** 接口的对象的自然顺序相反。第二个版本颠倒了所提供的 **Comparator** 的顺序。 |
2527+
| **rotate(List, int distance)** | 将所有元素向前移动 **distance** ,将尾部的元素移到开头。(译者注:即循环移动) |
2528+
| **shuffle(List)** <br><br> **shuffle(List, Random)** | 随机置换指定列表(即打乱顺序)。第一个版本使用了默认的随机化源,或者也可以使用第二个版本,提供自己的随机化源。 |
2529+
| **sort(List\<T>)** <br><br> **sort(List\<T>, Comparator\<? super T> c)** | 第一个版本使用元素的自然顺序排序该 **List\<T>** 。第二个版本根据提供的 **Comparator** 排序。 |
2530+
| **copy(List\<? super T> dest, List\<? extends T> src)** | 将 **src** 中的元素复制到 **dest** 。 |
2531+
| **swap(List, int i, int j)** | 交换 **List** 中位置 **i** 和 位置 **j** 的元素。可能比你手工编写的速度快。 |
2532+
| **fill(List\<? super T>, T x)** | 用 **x** 替换 **List** 中的所有元素。|
2533+
| **nCopies(int n, T x)** | 返回大小为 **n** 的不可变 **List\<T>** ,其引用都指向 **x** 。 |
2534+
| **disjoint(Collection, Collection)** | 如果两个集合没有共同元素,则返回 **true** 。 |
2535+
| **frequency(Collection, Object x)** | 返回 **Collection** 中,等于 **x** 的元素个数。 |
2536+
| **emptyList()** <br><br> **emptyMap()** <br><br> **emptySet()** | 返回不可变的空 **List** , **Map** 或 **Set** 。这些是泛型的,因此生成的 **Collection** 可以被参数化为所需的类型。 |
2537+
| **singleton(T x)** <br><br> **singletonList(T x)** <br><br> **singletonMap(K key, V value)** | 生成一个不可变的 **List** , **Set** 或 **Map** ,其中只包含基于给定参数的单个元素。 |
2538+
| **list(Enumeration\<T> e)** | 生成一个 **ArrayList\<T>** ,其中元素为(旧式) **Enumeration** ( **Iterator** 的前身)中的元素。用于从遗留代码向新式转换。 |
2539+
| **enumeration(Collection\<T>)** | 为参数集合生成一个旧式的 **Enumeration\<T>** 。 |
2540+
2541+
请注意, `min()` 和 `max()` 使用 **Collection** 对象,而不使用 **List** ,因此不必担心是否应对 **Collection** 进行排序。(如前所述,在执行 `binarySearch()` 之前,将会对 **List** 或数组进行`sort()` 排序。)
2542+
2543+
下面是一个示例,展示了上表中大多数实用工具程序的基本用法:
2544+
2545+
```java
2546+
// collectiontopics/Utilities.java
2547+
// Simple demonstrations of the Collections utilities
2548+
import java.util.*;
2549+
2550+
public class Utilities {
2551+
static List<String> list = Arrays.asList(
2552+
"one Two three Four five six one".split(" "));
2553+
public static void main(String[] args) {
2554+
System.out.println(list);
2555+
System.out.println("'list' disjoint (Four)?: " +
2556+
Collections.disjoint(list,
2557+
Collections.singletonList("Four")));
2558+
System.out.println(
2559+
"max: " + Collections.max(list));
2560+
System.out.println(
2561+
"min: " + Collections.min(list));
2562+
System.out.println(
2563+
"max w/ comparator: " + Collections.max(list,
2564+
String.CASE_INSENSITIVE_ORDER));
2565+
System.out.println(
2566+
"min w/ comparator: " + Collections.min(list,
2567+
String.CASE_INSENSITIVE_ORDER));
2568+
List<String> sublist =
2569+
Arrays.asList("Four five six".split(" "));
2570+
System.out.println("indexOfSubList: " +
2571+
Collections.indexOfSubList(list, sublist));
2572+
System.out.println("lastIndexOfSubList: " +
2573+
Collections.lastIndexOfSubList(list, sublist));
2574+
Collections.replaceAll(list, "one", "Yo");
2575+
System.out.println("replaceAll: " + list);
2576+
Collections.reverse(list);
2577+
System.out.println("reverse: " + list);
2578+
Collections.rotate(list, 3);
2579+
System.out.println("rotate: " + list);
2580+
List<String> source =
2581+
Arrays.asList("in the matrix".split(" "));
2582+
Collections.copy(list, source);
2583+
System.out.println("copy: " + list);
2584+
Collections.swap(list, 0, list.size() - 1);
2585+
System.out.println("swap: " + list);
2586+
Collections.shuffle(list, new Random(47));
2587+
System.out.println("shuffled: " + list);
2588+
Collections.fill(list, "pop");
2589+
System.out.println("fill: " + list);
2590+
System.out.println("frequency of 'pop': " +
2591+
Collections.frequency(list, "pop"));
2592+
List<String> dups =
2593+
Collections.nCopies(3, "snap");
2594+
System.out.println("dups: " + dups);
2595+
System.out.println("'list' disjoint 'dups'?: " +
2596+
Collections.disjoint(list, dups));
2597+
// Getting an old-style Enumeration:
2598+
Enumeration<String> e =
2599+
Collections.enumeration(dups);
2600+
Vector<String> v = new Vector<>();
2601+
while(e.hasMoreElements())
2602+
v.addElement(e.nextElement());
2603+
// Converting an old-style Vector
2604+
// to a List via an Enumeration:
2605+
ArrayList<String> arrayList =
2606+
Collections.list(v.elements());
2607+
System.out.println("arrayList: " + arrayList);
2608+
}
2609+
}
2610+
/* Output:
2611+
[one, Two, three, Four, five, six, one]
2612+
'list' disjoint (Four)?: false
2613+
max: three
2614+
min: Four
2615+
max w/ comparator: Two
2616+
min w/ comparator: five
2617+
indexOfSubList: 3
2618+
lastIndexOfSubList: 3
2619+
replaceAll: [Yo, Two, three, Four, five, six, Yo]
2620+
reverse: [Yo, six, five, Four, three, Two, Yo]
2621+
rotate: [three, Two, Yo, Yo, six, five, Four]
2622+
copy: [in, the, matrix, Yo, six, five, Four]
2623+
swap: [Four, the, matrix, Yo, six, five, in]
2624+
shuffled: [six, matrix, the, Four, Yo, five, in]
2625+
fill: [pop, pop, pop, pop, pop, pop, pop]
2626+
frequency of 'pop': 7
2627+
dups: [snap, snap, snap]
2628+
'list' disjoint 'dups'?: true
2629+
arrayList: [snap, snap, snap]
2630+
*/
2631+
```
2632+
2633+
输出解释了每种实用方法的行为。请注意由于大小写的缘故,普通版本的 `min()` 和 `max()` 与带有 **String.CASE_INSENSITIVE_ORDER** 比较器参数的版本的区别。
2634+
2635+
<!-- Sorting and Searching Lists -->
2636+
### 排序和搜索列表
2637+
2638+
用于执行排序和搜索 **List** 的实用工具程序与用于排序对象数组的程序具有相同的名字和方法签名,只不过是 **Collections** 的静态方法而不是 **Arrays** 。 这是一个使用 **Utilities.java** 中的 **list** 数据的示例:
2639+
2640+
```java
2641+
// collectiontopics/ListSortSearch.java
2642+
// Sorting/searching Lists with Collections utilities
2643+
import java.util.*;
2644+
2645+
public class ListSortSearch {
2646+
public static void main(String[] args) {
2647+
List<String> list =
2648+
new ArrayList<>(Utilities.list);
2649+
list.addAll(Utilities.list);
2650+
System.out.println(list);
2651+
Collections.shuffle(list, new Random(47));
2652+
System.out.println("Shuffled: " + list);
2653+
// Use ListIterator to trim off last elements:
2654+
ListIterator<String> it = list.listIterator(10);
2655+
while(it.hasNext()) {
2656+
it.next();
2657+
it.remove();
2658+
}
2659+
System.out.println("Trimmed: " + list);
2660+
Collections.sort(list);
2661+
System.out.println("Sorted: " + list);
2662+
String key = list.get(7);
2663+
int index = Collections.binarySearch(list, key);
2664+
System.out.println(
2665+
"Location of " + key + " is " + index +
2666+
", list.get(" + index + ") = " +
2667+
list.get(index));
2668+
Collections.sort(list,
2669+
String.CASE_INSENSITIVE_ORDER);
2670+
System.out.println(
2671+
"Case-insensitive sorted: " + list);
2672+
key = list.get(7);
2673+
index = Collections.binarySearch(list, key,
2674+
String.CASE_INSENSITIVE_ORDER);
2675+
System.out.println(
2676+
"Location of " + key + " is " + index +
2677+
", list.get(" + index + ") = " +
2678+
list.get(index));
2679+
}
2680+
}
2681+
/* Output:
2682+
[one, Two, three, Four, five, six, one, one, Two,
2683+
three, Four, five, six, one]
2684+
Shuffled: [Four, five, one, one, Two, six, six, three,
2685+
three, five, Four, Two, one, one]
2686+
Trimmed: [Four, five, one, one, Two, six, six, three,
2687+
three, five]
2688+
Sorted: [Four, Two, five, five, one, one, six, six,
2689+
three, three]
2690+
Location of six is 7, list.get(7) = six
2691+
Case-insensitive sorted: [five, five, Four, one, one,
2692+
six, six, three, three, Two]
2693+
Location of three is 7, list.get(7) = three
2694+
*/
2695+
```
2696+
2697+
就像使用数组进行搜索和排序一样,如果使用 **Comparator** 进行排序,则必须使用相同的 **Comparator** 执行 `binarySearch()` 。
2698+
2699+
该程序还演示了 **Collections** 中的 `shuffle()` 方法,该方法随机打乱了 **List** 的顺序。 **ListIterator** 是在打乱后的列表中的特定位置创建的,用于从该位置删除元素,直到列表末尾。
2700+
2701+
<!-- Making a Collection or Map Unmodifiable -->
2702+
### 创建不可修改的 Collection 或 Map
2703+
2704+
通常,创建 **Collection** 或 **Map** 的只读版本会很方便。 **Collections** 类通过将原始集合传递给一个方法然后返回一个只读版本的集合。 对于 **Collection** (如果不能将 **Collection** 视为更具体的类型), **List** , **Set** 和 **Map** ,这类方法有许多变体。这个示例展示了针对每种类型,正确构建只读版本集合的方法:
2705+
2706+
```java
2707+
// collectiontopics/ReadOnly.java
2708+
// Using the Collections.unmodifiable methods
2709+
import java.util.*;
2710+
import onjava.*;
2711+
2712+
public class ReadOnly {
2713+
static Collection<String> data =
2714+
new ArrayList<>(Countries.names(6));
2715+
public static void main(String[] args) {
2716+
Collection<String> c =
2717+
Collections.unmodifiableCollection(
2718+
new ArrayList<>(data));
2719+
System.out.println(c); // Reading is OK
2720+
//- c.add("one"); // Can't change it
2721+
2722+
List<String> a = Collections.unmodifiableList(
2723+
new ArrayList<>(data));
2724+
ListIterator<String> lit = a.listIterator();
2725+
System.out.println(lit.next()); // Reading is OK
2726+
//- lit.add("one"); // Can't change it
2727+
2728+
Set<String> s = Collections.unmodifiableSet(
2729+
new HashSet<>(data));
2730+
System.out.println(s); // Reading is OK
2731+
//- s.add("one"); // Can't change it
2732+
2733+
// For a SortedSet:
2734+
Set<String> ss =
2735+
Collections.unmodifiableSortedSet(
2736+
new TreeSet<>(data));
2737+
2738+
Map<String,String> m =
2739+
Collections.unmodifiableMap(
2740+
new HashMap<>(Countries.capitals(6)));
2741+
System.out.println(m); // Reading is OK
2742+
//- m.put("Ralph", "Howdy!");
2743+
2744+
// For a SortedMap:
2745+
Map<String,String> sm =
2746+
Collections.unmodifiableSortedMap(
2747+
new TreeMap<>(Countries.capitals(6)));
2748+
}
2749+
}
2750+
/* Output:
2751+
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO,
2752+
BURUNDI]
2753+
ALGERIA
2754+
[BENIN, BOTSWANA, ANGOLA, BURKINA FASO, ALGERIA,
2755+
BURUNDI]
2756+
{BENIN=Porto-Novo, BOTSWANA=Gaberone, ANGOLA=Luanda,
2757+
BURKINA FASO=Ouagadougou, ALGERIA=Algiers,
2758+
BURUNDI=Bujumbura}
2759+
*/
2760+
```
2761+
2762+
为特定类型调用 “unmodifiable” 方法不会导致编译时检查,但是一旦发生转换,对修改特定集合内容的任何方法调用都将产生 **UnsupportedOperationException** 异常。
2763+
2764+
在每种情况下,在将集合设置为只读之前,必须使用有意义的数据填充集合。填充完成后,最好的方法是用 “unmodifiable” 方法调用生成的引用替换现有引用。这样,一旦使得内容无法修改,那么就不会冒有意外更改内容的风险。另一方面,此工具还允许将可修改的集合保留为类中的**私有**集合,并从方法调用处返回对该集合的只读引用。所以,你可以在类内修改它,但其他人只能读它。
2765+
2766+
<!-- Synchronizing a Collection or Map -->
2767+
### 同步 Collection 或 Map
2768+
2769+
**synchronized** 关键字是多线程主题的重要组成部分,更复杂的内容在[第二十四章 并发编程]()中介绍。在这里,只需要注意到 **Collections** 类包含一种自动同步整个集合的方法。 语法类似于 “unmodifiable” 方法:
2770+
2771+
```java
2772+
// collectiontopics/Synchronization.java
2773+
// Using the Collections.synchronized methods
2774+
import java.util.*;
2775+
2776+
public class Synchronization {
2777+
public static void main(String[] args) {
2778+
Collection<String> c =
2779+
Collections.synchronizedCollection(
2780+
new ArrayList<>());
2781+
List<String> list = Collections
2782+
.synchronizedList(new ArrayList<>());
2783+
Set<String> s = Collections
2784+
.synchronizedSet(new HashSet<>());
2785+
Set<String> ss = Collections
2786+
.synchronizedSortedSet(new TreeSet<>());
2787+
Map<String,String> m = Collections
2788+
.synchronizedMap(new HashMap<>());
2789+
Map<String,String> sm = Collections
2790+
.synchronizedSortedMap(new TreeMap<>());
2791+
}
2792+
}
2793+
```
2794+
2795+
最好立即通过适当的 “synchronized” 方法传递新集合,如上所示。这样,就不会意外地暴露出非同步版本。
2796+
2797+
<!-- Fail Fast -->
2798+
#### Fail Fast
2799+
2800+
Java 集合还具有防止多个进程修改集合内容的机制。如果当前正在迭代集合,然后有其他一些进程介入并插入,删除或更改该集合中的对象,则会出现此问题。也许在集合中已经遍历过了那个元素,也许还没有遍历到,也许在调用 `size()` 之后集合的大小会缩小...有许多灾难情景。 Java 集合库使用一种 *fail-fast* 的机制,该机制可以检测到除了当前进程引起的更改之外,其它任何对集合的更改操作。如果它检测到其他人正在修改集合,则会立即生成 **ConcurrentModificationException** 异常。这就是“fail-fast”的含义——它不会在以后使用更复杂的算法尝试检测问题(快速失败)。
2801+
2802+
通过创建迭代器并向迭代器指向的集合中添加元素,可以很容易地看到操作中的 fail-fast 机制,如下所示:
2803+
2804+
```java
2805+
// collectiontopics/FailFast.java
2806+
// Demonstrates the "fail-fast" behavior
2807+
import java.util.*;
2808+
2809+
public class FailFast {
2810+
public static void main(String[] args) {
2811+
Collection<String> c = new ArrayList<>();
2812+
Iterator<String> it = c.iterator();
2813+
c.add("An object");
2814+
try {
2815+
String s = it.next();
2816+
} catch(ConcurrentModificationException e) {
2817+
System.out.println(e);
2818+
}
2819+
}
2820+
}
2821+
/* Output:
2822+
java.util.ConcurrentModificationException
2823+
*/
2824+
```
2825+
2826+
异常来自于在从集合中获得迭代器之后,又尝试在集合中添加元素。程序的两个部分可能会修改同一个集合,这种可能性的存在会产生不确定状态,因此异常会通知你更改代码。在这种情况下,应先将所有元素添加到集合,然后再获取迭代器。
2827+
2828+
**ConcurrentHashMap** , **CopyOnWriteArrayList** 和 **CopyOnWriteArraySet** 使用了特定的技术来避免产生 **ConcurrentModificationException** 异常。
25152829

25162830
<!-- Holding References -->
25172831
## 持有引用

0 commit comments

Comments
 (0)