Java Array vs. ArrayList: Comparison and Conversion

In Java programming, arrays and arraylists are two fundamental data structures often used to store collections of elements. Although both are used for the same purposes, their distinct characteristics significantly impact application performance and flexibility.

This Java tutorial explores the important features of arrays and arraylists, their respective strengths and weaknesses and different techniques of converting between both two structures facilitating seamless transitions when required.

1. Introduction

In Java, ArrayList is part of the collection framework and implementation of resizable array data structure. It means that the arraylist internally maintains an array that grows or shrinks dynamically when needed.

1.1. Java Arrays

An array is a fixed-sized data structure that stores elements of the same data type in a contiguous memory location. Each element in an array is identified by an index or a position, starting from 0 for the first element.

The arrays in Java are the same as seen in other programming languages. Typically, arrays have the following features:

  • Arrays always store elements of the same data type. The array type is declared at the time of initialization.
  • An array of integers can store only integer values. The Java compiler will not allow storing strings in this integer array.
  • Each element in the array is accessed only using an index. There is no other way to access the elements of the array.
  • Array size is always fixed and cannot be changed. To store more elements that array size, we must create a new array and copy the elements from the old array into the new array. When we try to add more than its size, it throws¬†ArrayIndexOutOfBoundsException.

For example, the internal memory representation of the following array is as follows:

int[] a = new int[5];

a[0] = 1;
a[1] = 2;
a[2] = 4;
a[3] = 8;
a[4] = 16;
Array in memory

Arrays have a fixed size, meaning that once an array is created, its size cannot be changed. Each element in the array is accessed using its corresponding index.

for(int i = 0; i < a.length; i++) {

  System.out.println(a[i]);
}

1.2. Java ArrayList

The ArrayList class is part of the Java collections framework and implements the List interface. Unlike arrays, ArrayLists can grow or shrink dynamically as elements are added or removed.

It is possible to store elements of multiple types in an arraylist, but most often is discouraged as it can cause ClassCastException in runtime when we fetch the elements from the array. To enforce type-safety, generics are used to declare the types of elements stored in the arraylist.

List<Integer> arraylist = new ArrayList<>();

arraylist.add(1);   // allowed

//arraylist.add("one");   // NOT allowed

Apart from the sequential access using for-loop, arraylists allow to iterate over elements using the iterators such as ListIterator. When we use iterators and modify the collection using iterators, it does not through the ConcurrentModificationException.

List<Integer> arraylist = new ArrayList<>();

arraylist.add(1);
arraylist.add(2);
arraylist.add(3);

//1 - using foreach loop
arraylist.forEach(System.out::println);

//2 - using iterator
ListIterator<Integer> listIterator = arraylist.listIterator();
while (listIterator.hasNext()) {

  System.out.println(listIterator.next());
}

2. Differences between Array and ArrayList in Java

The following table summarizes the comparison between arrays and arraylists. It compares both data structures on the basis of their performances, ease of use and usecases.

FeatureArraysArrayLists
Fixed-size vs Dynamic resizingAllocated with a fixed size during initializationDynamically resize as elements are added or removed
Memory Management and EfficiencyFixed-size can lead to memory wastage if the array size exceeds the actual number of elements it holds.Dynamic resizing incurs a slight performance overhead with optimized memory usage.
Syntax and ease of useA straight syntax for initialization, add, remove, and update operations.A more intuitive and convenient way to work using Collections API methods.
PerformanceFor read/write operations, arrays are generally faster due to direct access to elements using indices.
For write operations, where resizing is needed, arraylists can outperform arrays.
Except for write operations that require resizing, arraylists perform worse than arrays.
Type safetyArrays have limited type safety and allow storing elements of any type in the same array.ArrayLists provide better type safety through the use of generics, ensuring that only elements of a specific type can be stored.
Best used forUse Arrays when a fixed-size collection is required, and memory efficiency is critical.ArrayLists are best used for small collections where convenience is prioritized over small and negligible performance gains.

3. Convert Array to ArrayList

The most straightforward way to convert an array into an ArrayList is by using the Arrays.asList() method that creates a List view of the array, and then we create a new ArrayList using the ArrayList constructor. This effectively converts the array into an ArrayList.

String[] array = {"apple", "banana", "cherry"};

ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(array));

Alternatively, we can also use the Java 8 streams to iterate over array elements and collect them into a new ArrayList. It gives us a chance to perform additional operations on each element of the array before collecting them into the list.

ArrayList<String> arrayList = Arrays.stream(array)
		//additional actions
		.collect(Collectors.toCollection(ArrayList::new));

4. Convert ArrayList to Array

The simplest solution to convert an arraylist to an array is using the ArrayList.toArray() method an array containing all of the elements in the list in proper sequence. The toArray() returns an array of type Object[], so you need to provide the type of the desired array as an argument to the toArray() method.

The size of the new array is determined by the size of the ArrayList.

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("apple");
arrayList.add("banana");
arrayList.add("cherry");

String[] array = arrayList.toArray(new String[arrayList.size()]);

5. Best Practices and Recommendations

Both, ArrayLists and arrays, serve almost similar purposes and have their own advantages over the other. The following recommendations should help us in narrowing down and choosing the correct data structure for our application.

5.1. Frequency of resizing operations

If array resizing is frequently needed due to specific requirements, it is advisable to use the ArrayList. The internal handling of resizing operations takes away the complexity from the application code and provides almost similar performance gains over doing it manually.

5.2. Qualtifiable Performance Gains

If the performance gains are not significantly higher, then choosing arraylists over arrays is always recommended. ArrayLists take away the complexity and make the code more readable and provide almost similar performance for small collections.

The best way to gauge the performance gains is to measure it using any tool such as JMH.

5.3. Primitives vs Wrapper Objects

Arrays can directly work with primitives types where as arraylists work with objects, i.e. wrapper class in this case. If there is constant conversion needed between both types in the application while processing them, it is best to use arrays as they will simplify the code by removing the unnecessary type casting, and slight performance gains due to this.

int[] array = new int[10];

//Creating arraylist for 'int' type is not possible. We must create arraylist of type 'Integer'

ArrayList<Integer> arraylist = new ArrayList<>();

5.4. Interoperability with Other Collection Types

The ArrayList is part of Java collection frameworks and thus works seamlessly with other types such as Map, Set etc. Using arrays will introduce unnecessary and additional steps to convert between other collection types.

Using an arraylist will reduce such conversions and thus will produce more readable and concise code.

6. Conclusion

In conclusion, Java development best practices more often recommend using ArrayLists and other inbuilt collection classes due to their flexibility, ease of use and similar performance for small to medium-sized collections.

However, there are cases where arrays can be more appropriate, especially when performance or memory efficiency is a primary concern.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.