Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Adding an Element to a Java Array vs an ArrayList

$
0
0

1. Overview

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

2. Java Arrays and 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.

2.1. Accessing and Modifying Elements

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:

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

2.2. Fixed vs Dynamic Size

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.

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.

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.

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.

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

2.3. Element Types

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.

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.

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

3. Appending an Element

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:

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:

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:

anArrayList.add(newElement);

4. Inserting an Element at Index

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:

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.

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

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

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:

anArrayList.add(index, newElement);

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

5. Conclusion

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.

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


Viewing all articles
Browse latest Browse all 4536

Trending Articles