Guide to the java.util.Arrays Class – java.util.Arrays类指南

最后修改: 2018年 6月 13日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this tutorial, we’ll take a look at java.util.Arrays, a utility class that has been part of Java since Java 1.2.

在本教程中,我们将看看java.util.Arrays,一个从Java 1.2开始就属于Java的实用类。

Using Arrays, we can create, compare, sort, search, stream, and transform arrays.

使用Arrays,我们可以创建、比较、排序、搜索、流和转换数组。

2. Creating

2.创建

Let’s take a look at some of the ways we can create arrays: copyOf, copyOfRange, and fill.

让我们来看看我们可以创建数组的一些方法。copyOf, copyOfRange, 和fill.

2.1. copyOf and copyOfRange

2.1.copyOfcopyOfRange

To use copyOfRange, we need our original array and the beginning index (inclusive) and end index (exclusive) that we want to copy:

要使用copyOfRange,我们需要我们的原始数组和我们想要复制的开始索引(包括)和结束索引(不包括)。

String[] intro = new String[] { "once", "upon", "a", "time" };
String[] abridgement = Arrays.copyOfRange(storyIntro, 0, 3); 

assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement); 
assertFalse(Arrays.equals(intro, abridgement));

And to use copyOf, we’d take intro and a target array size and we’d get back a new array of that length:

要使用copyOf,我们需要intro和一个目标数组大小,我们将得到一个该长度的新数组。

String[] revised = Arrays.copyOf(intro, 3);
String[] expanded = Arrays.copyOf(intro, 5);

assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised);
assertNull(expanded[4]);

Note that copyOf pads the array with nulls if our target size is bigger than the original size.

请注意,copyOf 如果我们的目标尺寸大于原始尺寸,则会用nulls填充数组。

2.2. fill

2.2.填补

Another way, we can create a fixed-length array, is fill, which is useful when we want an array where all elements are the same:

另一种方法,我们可以创建一个固定长度的数组,就是fill,当我们想要一个所有元素都相同的数组时,这个方法很有用。

String[] stutter = new String[3];
Arrays.fill(stutter, "once");

assertTrue(Stream.of(stutter)
  .allMatch(el -> "once".equals(el));

Check out setAll to create an array where the elements are different.

检查一下setAll ,创建一个元素不同的数组。

Note that we need to instantiate the array ourselves beforehand–as opposed to something like String[] filled = Arrays.fill(“once”, 3);–since this feature was introduced before generics were available in the language.

请注意,我们需要事先自己实例化数组–而不是像String[] filled = Arrays.fill(“once”, 3);–因为这个功能是在语言中出现泛型之前引入的。

3. Comparing

3.比较

Now let’s switch to methods for comparing arrays.

现在让我们转到比较数组的方法。

3.1. equals and deepEquals

3.1.equalsdeepEquals

We can use equals for simple array comparison by size and contents.  If we add a null as one of the elements, the content check fails:

我们可以使用equals进行简单的数组大小和内容比较。 如果我们添加一个null作为其中一个元素,内容检查就会失败。

assertTrue(
  Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro));
assertFalse(
  Arrays.equals(new String[] { "once", "upon", "a", null }, intro));

When we have nested or multi-dimensional arrays, we can use deepEquals to not only check the top-level elements but also perform the check recursively:

当我们有嵌套或多维数组时,我们可以使用deepEquals不仅检查顶层元素,还可以递归地执行检查。

Object[] story = new Object[] 
  { intro, new String[] { "chapter one", "chapter two" }, end };
Object[] copy = new Object[] 
  { intro, new String[] { "chapter one", "chapter two" }, end };

assertTrue(Arrays.deepEquals(story, copy));
assertFalse(Arrays.equals(story, copy));

Note how deepEquals passes but equals fails.

请注意deepEquals如何通过,但equalsfails。

This is because deepEquals ultimately calls itself each time it encounters an array, while equals will simply compare sub-arrays’ references.

这是因为deepEquals在每次遇到数组时都会调用自己,而equals会简单地比较子数组的引用。

Also, this makes it dangerous to call on an array with a self-reference!

另外,这也使得在数组上调用自指的时候很危险!

3.2. hashCode and deepHashCode

3.2.hashCodedeepHashCode

The implementation of hashCode will give us the other part of the equals/hashCode contract that is recommended for Java objects.  We use hashCode to compute an integer based on the contents of the array:

hashCode的实现将给我们提供equals/hashCode契约的另一部分,该契约被推荐用于Java对象。 我们使用hashCode来根据数组的内容计算一个整数。

Object[] looping = new Object[]{ intro, intro }; 
int hashBefore = Arrays.hashCode(looping);
int deepHashBefore = Arrays.deepHashCode(looping);

Now, we set an element of the original array to null and recompute the hash values:

现在,我们将原数组的一个元素设置为空,并重新计算哈希值。

intro[3] = null;
int hashAfter = Arrays.hashCode(looping);

Alternatively, deepHashCode checks the nested arrays for matching numbers of elements and contents.  If we recalculate with deepHashCode:

另外,deepHashCode检查嵌套数组的元素数量和内容是否匹配。 如果我们用deepHashCode重新计算。

int deepHashAfter = Arrays.deepHashCode(looping);

Now, we can see the difference in the two methods:

现在,我们可以看到这两种方法的区别。

assertEquals(hashAfter, hashBefore);
assertNotEquals(deepHashAfter, deepHashBefore);

deepHashCode is the underlying calculation used when we are working with data structures like HashMap and HashSet on arrays.

deepHashCode是我们在处理数据结构如HashMapHashSet数组时使用的基础计算

4. Sorting and Searching

4.分类和搜索

Next, let’s take a look at sorting and searching arrays.

接下来,让我们来看看数组的排序和搜索。

4.1. sort

4.1.排序

If our elements are either primitives or they implement Comparable, we can use sort to perform an in-line sort:

如果我们的元素是基元或者它们实现了Comparable,我们可以使用sort来执行在线排序。

String[] sorted = Arrays.copyOf(intro, 4);
Arrays.sort(sorted);

assertArrayEquals(
  new String[]{ "a", "once", "time", "upon" }, 
  sorted);

Take care that sort mutates the original reference, which is why we perform a copy here.

注意,sort会突变原始引用,这就是为什么我们在这里进行复制。

sort will use a different algorithm for different array element types. Primitive types use a dual-pivot quicksort and Object types use Timsort. Both have the average case of O(n log(n)) for a randomly-sorted array.

排序对于不同的数组元素类型将使用不同的算法。原始类型使用双支点quicksort对象类型使用Timsort。对于一个随机排序的数组,两者的平均情况都是O(n log(n))

As of Java 8, parallelSort is available for a parallel sort-merge.  It offers a concurrent sorting method using several Arrays.sort tasks.

从Java 8开始,parallelSort 可用于并行排序-合并。 它提供了一种使用多个Arrays.sort任务的并发排序方法。

4.2. binarySearch

4.2.二进制搜索

Searching in an unsorted array is linear, but if we have a sorted array, then we can do it in O(log n), which is what we can do with binarySearch:

在未排序的数组中搜索是线性的,但如果我们有一个排序的数组,那么我们可以在O(log n)中完成,这就是我们可以用binarySearch:做的事情。

int exact = Arrays.binarySearch(sorted, "time");
int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase);

assertEquals("time", sorted[exact]);
assertEquals(2, exact);
assertEquals(exact, caseInsensitive);

If we don’t provide a Comparator as a third parameter, then binarySearch counts on our element type being of type Comparable.

如果我们不提供一个 Comparator 作为第三个参数,那么 binarySearch 就指望我们的元素类型是 Comparable 类型。

And again, note that if our array isn’t first sorted, then binarySearch won’t work as we expect!

而且再次注意,如果我们的数组没有首先排序,那么binarySearch 就不会像我们期望的那样工作!

5. Streaming

5.流媒体

As we saw earlier, Arrays was updated in Java 8 to include methods using the Stream API such as parallelSort (mentioned above), stream and setAll.

正如我们之前看到的,Arrays 在Java 8中被更新,以包括使用Stream API的方法,如parallelSort(上文提及)、stream setAll.

5.1. stream

5.1.

stream gives us full access to the Stream API for our array:

stream让我们能够完全访问我们的数组的Stream API。

Assert.assertEquals(Arrays.stream(intro).count(), 4);

exception.expect(ArrayIndexOutOfBoundsException.class);
Arrays.stream(intro, 2, 1).count();

We can provide inclusive and exclusive indices for the stream however we should expect an ArrayIndexOutOfBoundsException if the indices are out of order,  negative, or out of range.

我们可以为流提供包容性和排他性指数,但是如果指数不符合顺序、为负数或者超出范围,我们应该期待一个ArrayIndexOutOfBoundsException

6. Transforming

6.转型

Finally, toString, asList, and setAll give us a couple different ways to transform arrays.

最后,toString, asList,setAll为我们提供了几种不同的方法来转换数组。

6.1. toString and deepToString

6.1.toStringdeepToString

A great way we can get a readable version of our original array is with toString:

我们可以通过toString:获得原始数组的可读版本,这是一个很好的方法。

assertEquals("[once, upon, a, time]", Arrays.toString(storyIntro));

Again we must use the deep version to print the contents of nested arrays:

同样,我们必须使用深度版本来打印嵌套数组的内容

assertEquals(
  "[[once, upon, a, time], [chapter one, chapter two], [the, end]]",
  Arrays.deepToString(story));

6.2. asList

6.2.asList

Most convenient of all the Arrays methods for us to use is the asList. We have an easy way to turn an array into a list:

在所有的Arrays方法中,最方便我们使用的是asList.我们有一个简单的方法来把数组变成一个列表。

List<String> rets = Arrays.asList(storyIntro);

assertTrue(rets.contains("upon"));
assertTrue(rets.contains("time"));
assertEquals(rets.size(), 4);

However, the returned List will be a fixed length so we won’t be able to add or remove elements.

然而,返回的List将是一个固定的长度,所以我们将无法添加或删除元素

Note also that, curiously, java.util.Arrays has its own ArrayList subclass, which asList returns. This can be very deceptive when debugging!

还要注意,奇怪的是,java.util.Arrays有自己的ArrayList子类,asList返回。在调试的时候,这可能是非常具有欺骗性的!

6.3. setAll

6.3.setAll

With setAll, we can set all of the elements of an array with a functional interface. The generator implementation takes the positional index as a parameter:

通过setAll,我们可以用一个功能接口来设置一个数组的所有元素。生成器的实现将位置索引作为一个参数。

String[] longAgo = new String[4];
Arrays.setAll(longAgo, i -> this.getWord(i)); 
assertArrayEquals(longAgo, new String[]{"a","long","time","ago"});

And, of course, exception handling is one of the more dicey parts of using lambdas. So remember that here, if the lambda throws an exception, then Java doesn’t define the final state of the array.

当然,异常处理是使用lambdas的一个比较棘手的部分。所以请记住,在这里,如果lambda抛出一个异常,那么Java就不会定义数组的最终状态。

7. Parallel Prefix

7.平行前缀

Another new method in Arrays introduced since Java 8 is parallelPrefix. With parallelPrefix, we can operate on each element of the input array in a cumulative fashion.

自Java 8以来,Arrays中的另一个新方法是parallelPrefix。通过parallelPrefix,我们可以以累积的方式对输入数组的每个元素进行操作。

7.1. parallelPrefix

7.1.parallelPrefix

If the operator performs addition like in the following sample, [1, 2, 3, 4] will result in [1, 3, 6, 10]:

如果操作者像下面的例子那样执行加法,[1, 2, 3, 4] 将产生[1, 3, 6, 10]:

int[] arr = new int[] { 1, 2, 3, 4};
Arrays.parallelPrefix(arr, (left, right) -> left + right);
assertThat(arr, is(new int[] { 1, 3, 6, 10}));

Also, we can specify a subrange for the operation:

另外,我们还可以为操作指定一个子范围。

int[] arri = new int[] { 1, 2, 3, 4, 5 };
Arrays.parallelPrefix(arri, 1, 4, (left, right) -> left + right);
assertThat(arri, is(new int[] { 1, 2, 5, 9, 5 }));

Notice that the method is performed in parallel, so the cumulative operation should be side-effect-free and associative.

注意,该方法是并行执行的,所以累积操作应该是无副作用的,并且关联性

For a non-associative function:

对于一个非关联性的函数。

int nonassociativeFunc(int left, int right) {
    return left + right*left;
}

using parallelPrefix would yield inconsistent results:

使用parallelPrefix会产生不一致的结果。

@Test
public void whenPrefixNonAssociative_thenError() {
    boolean consistent = true;
    Random r = new Random();
    for (int k = 0; k < 100_000; k++) {
        int[] arrA = r.ints(100, 1, 5).toArray();
        int[] arrB = Arrays.copyOf(arrA, arrA.length);

        Arrays.parallelPrefix(arrA, this::nonassociativeFunc);

        for (int i = 1; i < arrB.length; i++) {
            arrB[i] = nonassociativeFunc(arrB[i - 1], arrB[i]);
        }

        consistent = Arrays.equals(arrA, arrB);
        if(!consistent) break;
    }
    assertFalse(consistent);
}

7.2. Performance

7.2.性能

Parallel prefix computation is usually more efficient than sequential loops, especially for large arrays. When running micro-benchmark on an Intel Xeon machine(6 cores) with JMH, we can see a great performance improvement:

并行前缀计算通常比顺序循环更有效,特别是对于大型阵列。当使用JMH在Intel Xeon机器(6核)上运行微型测试时,我们可以看到性能有很大的提高。

Benchmark                      Mode        Cnt       Score   Error        Units
largeArrayLoopSum             thrpt         5        9.428 ± 0.075        ops/s
largeArrayParallelPrefixSum   thrpt         5       15.235 ± 0.075        ops/s

Benchmark                     Mode         Cnt       Score   Error        Units
largeArrayLoopSum             avgt          5      105.825 ± 0.846        ops/s
largeArrayParallelPrefixSum   avgt          5       65.676 ± 0.828        ops/s

Here is the benchmark code:

下面是基准代码。

@Benchmark
public void largeArrayLoopSum(BigArray bigArray, Blackhole blackhole) {
  for (int i = 0; i < ARRAY_SIZE - 1; i++) {
    bigArray.data[i + 1] += bigArray.data[i];
  }
  blackhole.consume(bigArray.data);
}

@Benchmark
public void largeArrayParallelPrefixSum(BigArray bigArray, Blackhole blackhole) {
  Arrays.parallelPrefix(bigArray.data, (left, right) -> left + right);
  blackhole.consume(bigArray.data);
}

7. Conclusion

7.结论

In this article, we learned how some methods for creating, searching, sorting and transforming arrays using the java.util.Arrays class.

在这篇文章中,我们学习了如何使用java.util.Arrays类创建、搜索、排序和转换数组的一些方法。

This class has been expanded in more recent Java releases with the inclusion of stream producing and consuming methods in Java 8 and mismatch methods in Java 9.

这个类在最近的Java版本中得到了扩展,在Java 8中包含了流的产生和消耗方法,在Java 9中包含了错配方法。

The source for this article is, as always, over on Github.

这篇文章的来源一如既往地是Github上的