The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
The polymorphic algorithms described here are pieces of reusable functionality provided by the Java platform. 这里描述的多态算法是Java平台提供的可重用功能。All of them come from the 它们都来自Collections
class, and all take the form of static methods whose first argument is the collection on which the operation is to be performed. Collections
类,都采用静态方法的形式,其第一个参数是要对其执行操作的集合。The great majority of the algorithms provided by the Java platform operate on Java平台提供的绝大多数算法都在List
instances, but a few of them operate on arbitrary Collection
instances. List
实例上运行,但有少数算法在任意集合实例上运行。This section briefly describes the following algorithms:本节简要介绍以下算法:
The sort
algorithm reorders a List
so that its elements are in ascending order according to an ordering relationship. sort
算法对List
进行重新排序,使其元素根据排序关系按升序排列。Two forms of the operation are provided. 提供了两种操作形式。The simple form takes a 简单表单采用一个List
and sorts it according to its elements' natural ordering. List
,并根据其元素的自然顺序对其进行排序。If you're unfamiliar with the concept of natural ordering, read the Object Ordering section.如果你不熟悉自然排序的概念,请阅读对象排序部分。
The sort
operation uses a slightly optimized merge sort algorithm that is fast and stable:sort
操作使用了一种稍微优化的合并排序算法,该算法快速稳定:
n log(n)
time and runs substantially faster on nearly sorted lists. n log(n)
时间内运行,并且在几乎排序的列表上运行得更快。n log(n)
performance.n log(n)
性能。The following 下面这个trivial program
prints out its arguments in lexicographic (alphabetical) order.trivial program
按字典(字母)顺序打印参数。
import java.util.*; public class Sort { public static void main(String[] args) { List<String> list = Arrays.asList(args); Collections.sort(list); System.out.println(list); } }
Let's run the program.让我们运行这个程序。
% java Sort i walk the line
The following output is produced.产生以下输出。
[i, line, the, walk]
The program was included only to show you that algorithms really are as easy to use as they appear to be.包含该程序只是为了向您展示,算法真的像看上去那样易于使用。
The second form of sort
takes a Comparator
in addition to a List
and sorts the elements with the Comparator
. sort
的第二种形式是在列表之外使用Comparator
,并使用Comparator
对元素进行排序。Suppose you want to print out the anagram groups from our earlier example in reverse order of size largest anagram group first. 假设您想按大小的相反顺序打印出我们前面示例中的字谜组首先是最大的字谜组。The example that follows shows you how to achieve this with the help of the second form of the 下面的示例向您展示了如何借助sort
method.sort
方法的第二种形式来实现这一点。
Recall that the anagram groups are stored as values in a 回想一下,字谜组以Map
, in the form of List
instances. List
实例的形式存储为Map
中的值。The revised printing code iterates through the Map
's values view, putting every List
that passes the minimum-size test into a List
of List
s. Then the code sorts this List
, using a Comparator
that expects List
instances, and implements reverse size-ordering. Finally, the code iterates through the sorted List
, printing its elements (the anagram groups). The following code replaces the printing code at the end of the main
method in the Anagrams
example.
// Make a List of all anagram groups above size threshold. List<List<String>> winners = new ArrayList<List<String>>(); for (List<String> l : m.values()) if (l.size() >= minGroupSize) winners.add(l); // Sort anagram groups according to size Collections.sort(winners, new Comparator<List<String>>() { public int compare(List<String> o1, List<String> o2) { return o2.size() - o1.size(); }}); // Print anagram groups. for (List<String> l : winners) System.out.println(l.size() + ": " + l);
Running 在与the program
on the same dictionary
as in The Map Interface section, with the same minimum anagram group size (eight), produces the following output.Map
接口部分相同的字典上,以相同的最小字谜组大小(8)运行该程序,将生成以下输出。
12: [apers, apres, asper, pares, parse, pears, prase, presa, rapes, reaps, spare, spear] 11: [alerts, alters, artels, estral, laster, ratels, salter, slater, staler, stelar, talers] 10: [least, setal, slate, stale, steal, stela, taels, tales, teals, tesla] 9: [estrin, inerts, insert, inters, niters, nitres, sinter, triens, trines] 9: [capers, crapes, escarp, pacers, parsec, recaps, scrape, secpar, spacer] 9: [palest, palets, pastel, petals, plates, pleats, septal, staple, tepals] 9: [anestri, antsier, nastier, ratines, retains, retinas, retsina, stainer, stearin] 8: [lapse, leaps, pales, peals, pleas, salep, sepal, spale] 8: [aspers, parses, passer, prases, repass, spares, sparse, spears] 8: [enters, nester, renest, rentes, resent, tenser, ternes,��treens] 8: [arles, earls, lares, laser, lears, rales, reals, seral] 8: [earings, erasing, gainers, reagins, regains, reginas, searing, seringa] 8: [peris, piers, pries, prise, ripes, speir, spier, spire] 8: [ates, east, eats, etas, sate, seat, seta, teas] 8: [carets, cartes, caster, caters, crates, reacts, recast,��traces]
The shuffle
algorithm does the opposite of what sort
does, destroying any trace of order that may have been present in a List
. That is, this algorithm reorders the List
based on input from a source of randomness such that all possible permutations occur with equal likelihood, assuming a fair source of randomness. This algorithm is useful in implementing games of chance. For example, it could be used to shuffle a List
of Card
objects representing a deck. Also, it's useful for generating test cases.此外,它还可用于生成测试用例。
This operation has two forms: one takes a 此操作有两种形式:一种是获取列表并使用默认的随机性源,另一种是要求调用方提供随机对象以用作随机性源。List
and uses a default source of randomness, and the other requires the caller to provide a Random object to use as a source of randomness. The code for this algorithm is used as an example in the 该算法的代码在List
section. List
部分用作示例。
The Collections
class provides five algorithms for doing routine data manipulation on List
objects, all of which are pretty straightforward:Collections
类提供了五种算法,用于对List
对象执行例行数据操作,所有这些算法都非常简单:
reverse
List
.List
中元素的顺序。fill
List
with the specified value. List
中的每个元素。List
.List
很有用。copy
List
and a source List
, and copies the elements of the source into the destination, overwriting its contents. List
和一个源List
,并将源的元素复制到目标中,覆盖其内容。List
must be at least as long as the source. List
必须至少与源列表一样长。List
are unaffected.List
中的其余元素不受影响。swap
List
.List
中的指定位置交换元素。addAll
Collection
. Collection
中。The binarySearch
algorithm searches for a specified element in a sorted List
. binarySearch
算法在排序List
中搜索指定的元素。This algorithm has two forms. 该算法有两种形式。The first takes a 第一个是一个List
and an element to search for (the "search key"). List
和一个要搜索的元素(“搜索键”)。This form assumes that the 这种形式假设List
is sorted in ascending order according to the natural ordering of its elements. List
按照元素的自然顺序按升序排序。The second form takes a 第二种形式除了Comparator
in addition to the List
and the search key, and assumes that the List
is sorted into ascending order according to the specified Comparator
. List
和搜索键之外,还采用了一个Comparator
,并假设List
是根据指定的Comparator
按升序排序的。The sort
algorithm can be used to sort the List
prior to calling binarySearch
.sort
算法可用于在调用binarySearch
之前对List
进行排序。
The return value is the same for both forms. 两种形式的返回值相同。If the 如果List
contains the search key, its index is returned. List
包含搜索键,则返回其索引。If not, the return value is 如果不是,则返回值为(-(insertion point) - 1)
, where the insertion point is the point at which the value would be inserted into the List
, or the index of the first element greater than the value or list.size()
if all elements in the List
are less than the specified value. (-(insertion point) - 1)
,其中插入点是将该值插入List
的点,或者如果List
中的所有元素都小于指定值,则返回大于该值的第一个元素的索引或list.size()
。This admittedly ugly formula guarantees that the return value will be 这个公认的丑陋公式保证了当且仅当找到搜索键时,返回值将>= 0
if and only if the search key is found. >=0
。It's basically a hack to combine a boolean 基本上,将布尔(found)
and an integer (index)
into a single int
return value.(found)
和整数(index)
组合成一个int
返回值是一种技巧。
The following idiom, usable with both forms of the 下面的习惯用法可用于两种形式的binarySearch
operation, looks for the specified search key and inserts it at the appropriate position if it's not already present.binarySearch
操作,它会查找指定的搜索键,并将其插入到适当的位置(如果它尚未出现)。
int pos = Collections.binarySearch(list, key); if (pos < 0) l.add(-pos-1, key);
The frequency and disjoint algorithms test some aspect of the composition of one or more 频率和不相交算法测试一个或多个Collections
:Collections
组成的某些方面:
frequency
disjoint
Collections
are disjoint; that is, whether they contain no elements in commonCollections
是否不相交;也就是说,它们是否不包含共同元素The min
and the max
algorithms return, respectively, the minimum and maximum element contained in a specified Collection
. min
和max
算法分别返回指定Collection
中包含的最小和最大元素。Both of these operations come in two forms. 这两种操作都有两种形式。The simple form takes only a 简单表单只接受一个Collection
and returns the minimum (or maximum) element according to the elements' natural ordering. Collections
,并根据元素的自然顺序返回最小(或最大)元素。The second form takes a 第二种形式是在Comparator
in addition to the Collection
and returns the minimum (or maximum) element according to the specified Comparator
.Collection
之外使用一个Comparator
,并根据指定的Comparator
返回最小(或最大)元素。