Adding an Element to a Java Array vs an ArrayList – 在Java数组与ArrayList中添加一个元素

最后修改: 2019年 10月 20日

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

1. Overview

1.概述

In this tutorial, we’ll briefly look at the similarities and dissimilarities in memory allocation between Java arrays and the standard ArrayList. Furthermore, we’ll see how to append and insert elements in an array and ArrayList.

在本教程中,我们将简要地看看Java数组和标准ArrayList之间在内存分配方面的异同点。此外,我们将看到如何在数组和ArrayList中追加和插入元素。

2. Java Arrays and ArrayList

2.Java数组和ArrayList

A Java array is a basic data structure provided by the language. In contrast, ArrayList is an implementation of the List interface backed by an array and is provided in the Java Collections Framework.

Java 数组是一种由语言提供的基本数据结构。相比之下,ArrayList是由数组支持的List接口的实现,在Java集合框架中提供。

2.1. Accessing and Modifying Elements

2.1.访问和修改元素

We can access and modify array elements using the square brackets notation:

我们可以使用方括号符号访问和修改数组元素。

System.out.println(anArray[1]);
anArray[1] = 4;

On the other hand, ArrayList has a set of methods to access and modify elements:

另一方面,ArrayList有一组方法来访问和修改元素。

int n = anArrayList.get(1);
anArrayList.set(1, 4);

2.2. Fixed vs Dynamic Size

2.2.固定与动态尺寸

An array and the ArrayList both allocate heap memory in a similar manner, but what differs is that an array is fixed-sized, while the size of an ArrayList increases dynamically.

阵列和ArrayList都以类似的方式分配堆内存,但不同的是阵列是固定大小的,而ArrayList的大小是动态增加的。

Since a Java array is fixed-sized, we need to provide the size while instantiating it. It is not possible to increase the size of the array once it has been instantiated. Instead, we need to create a new array with the adjusted size and copy all the elements from the previous array.

由于Java数组是固定大小的,我们需要在实例化它的时候提供大小。一旦数组被实例化,就不可能再增加它的大小。相反,我们需要用调整后的大小创建一个新的数组,并从以前的数组中复制所有的元素。

ArrayList is a resizable array implementation of the List interface — that is, ArrayList grows dynamically as elements are added to it. When the number of current elements (including the new element to be added to the ArrayList) is greater than the maximum size of its underlying array, then the ArrayList increases the size of the underlying array.

ArrayListList接口的一个可调整大小的数组实现–也就是说,ArrayList会随着元素的添加而动态地增长。当当前元素的数量(包括将要添加到ArrayList中的新元素)大于其底层数组的最大尺寸时,那么ArrayList就会增加底层数组的尺寸。

The growth strategy for the underlying array depends on the implementation of the ArrayList. However, since the size of the underlying array cannot be increased dynamically, a new array is created and the old array elements are copied into the new array.

底层数组的增长策略取决于ArrayList的实现。然而,由于底层数组的大小不能动态地增加,所以要创建一个新的数组,并将旧的数组元素复制到新的数组中。

The add operation has a constant amortized time cost. In other words, adding n elements to an ArrayList requires O(n) time.

添加操作有一个恒定的摊销时间成本。换句话说,向ArrayList添加n元素需要O(n)时间。

2.3. Element Types

2.3 元素类型

An array can contain primitive as well as non-primitive data types, depending on the definition of the array. However, an ArrayList can only contain non-primitive data types.

一个数组可以包含原始数据类型,也可以包含非原始数据类型,这取决于数组的定义。然而,一个ArrayList只能包含非原始数据类型

When we insert elements with primitive data types into an ArrayList, the Java compiler automatically converts the primitive data type into its corresponding object wrapper class.

当我们在ArrayList中插入具有原始数据类型的元素时,Java编译器会自动将原始数据类型转换为其相应的对象封装类。

Let’s now look at how to append and insert elements in Java arrays and the ArrayList.

现在我们来看看如何在Java数组和ArrayList中追加和插入元素。

3. Appending an Element

3.追加一个元素

As we’ve already seen, arrays are of fixed size.

正如我们已经看到的,数组的大小是固定的。

So, to append an element, first, we need to declare a new array that is larger than the old array and copy the elements from the old array to the newly created array. After that, we can append the new element to this newly created array.

所以,要追加一个元素,首先,我们需要声明一个比旧数组大的新数组,并将旧数组中的元素复制到新创建的数组中。之后,我们可以将新的元素追加到这个新创建的数组中。

Let’s look at its implementation in Java without using any utility classes:

让我们看看它在Java中的实现,不使用任何实用类。

public Integer[] addElementUsingPureJava(Integer[] srcArray, int elementToAdd) {
    Integer[] destArray = new Integer[srcArray.length+1];

    for(int i = 0; i < srcArray.length; i++) {
        destArray[i] = srcArray[i];
    }

    destArray[destArray.length - 1] = elementToAdd;
    return destArray;
}

Alternately, the Arrays class provides a utility method copyOf(), which assists in creating a new array of larger size and copying all the elements from the old array:

另外,Arrays 类提供了一个实用方法copyOf(),它有助于创建一个更大的新数组,并从旧数组中复制所有元素。

int[] destArray = Arrays.copyOf(srcArray, srcArray.length + 1);

Once we have created a new array, we can easily append the new element to the array:

一旦我们创建了一个新的数组,我们就可以很容易地将新元素追加到数组中。

destArray[destArray.length - 1] = elementToAdd;

On the other hand, appending an element in ArrayList is quite easy:

另一方面,ArrayList中应用一个元素是非常容易的

anArrayList.add(newElement);

4. Inserting an Element at Index

4.在索引处插入一个元素

Inserting an element at a given index without losing the previously added elements is not a simple task in arrays.

在一个给定的索引处插入一个元素而不丢失之前添加的元素,在数组中不是一个简单的任务。

First of all, if the array already contains the number of elements equal to its size, then we first need to create a new array with a larger size and copy the elements over to the new array.

首先,如果数组中的元素数量已经等于其大小,那么我们首先需要创建一个更大的新数组,并将元素复制到新数组中。

Furthermore, we need to shift all elements that come after the specified index by one position to the right:

此外,我们需要将指定索引之后的所有元素向右移动一个位置。

public static int[] insertAnElementAtAGivenIndex(final int[] srcArray, int index, int newElement) {
    int[] destArray = new int[srcArray.length+1];
    int j = 0;
    for(int i = 0; i < destArray.length-1; i++) {

        if(i == index) {
            destArray[i] = newElement;
        } else {
            destArray[i] = srcArray[j];
            j++;
        }
    }
    return destArray;
}

However, the ArrayUtils class gives us a simpler solution to insert items into an array:

然而,ArrayUtils类给了我们一个更简单的解决方案,将项目插入一个数组

int[] destArray = ArrayUtils.insert(2, srcArray, 77);

We have to specify the index at which we want to insert the value, the source array, and the value to insert.

我们必须指定我们要插入值的索引,源数组,以及要插入的值。

The insert() method returns a new array containing a larger number of elements, with the new element at the specified index and all remaining elements shifted one position to the right.

insert()方法返回一个包含更大数量元素的新数组,新元素位于指定的索引,所有剩余的元素向右移动一个位置。

Note that the last argument of the insert() method is a variable argument, so we can insert any number of items into an array.

注意,insert()方法的最后一个参数是一个变量参数,所以我们可以在数组中插入任意数量的项目。

Let’s use it to insert three elements in srcArray starting at index two:

让我们用它在srcArray中插入三个元素,从索引2开始。

int[] destArray = ArrayUtils.insert(2, srcArray, 77, 88, 99);

And the remaining elements will be shifted three places to the right.

而剩下的元素将被向右移动三个位置。

Furthermore, this can be achieved trivially for the ArrayList:

此外,对于ArrayList来说,这可以通过简单的方式实现。

anArrayList.add(index, newElement);

ArrayList shifts the elements and inserts the element at the required location.

ArrayList移动元素并在所需位置插入元素。

5. Conclusion

5.总结

In this article, we looked at Java array and ArrayList. Furthermore, we looked at the similarities and differences between the two. Finally, we saw how to append and insert elements in an array and ArrayList.

在这篇文章中,我们研究了Java数组和ArrayList。此外,我们还研究了这两者之间的异同。最后,我们看到了如何在数组和ArrayList中追加和插入元素。

As always, the full source code of the working examples is available over on GitHub.

一如既往,工作实例的完整源代码可在GitHub上获得over