Java ArrayList to Array With Examples

Sometimes we have to convert ArrayList to Array in java program. Today we will look into different java ArrayList to Array conversion options.

Java ArrayList to Array

java-arraylist-to-array (1)

ArrayList in Java is backed by Array. So it’s no wonder, ArrayList provides utility methods to convert ArrayList to Array. Let’s look at a simple program showing how to convert ArrayList to an array in java.

If you will look into ArrayList methods, toArray method is overloaded. The other one is without any argument that returns Object array. However, it’s not recommended because then you will have to cast the object to proper type for any operations.

ArrayList to Array in Java – other ways

While passing the array as argument in toArray method, we don’t need to provide the array with exact size. Below code works fine too.

If you are using Java 8 or higher, you can use Stream too for converting ArrayList to Array.

Java ArrayList to Array – Shallow Copy

When we convert ArrayList to Array using above methods, it returns a shallow copy of the elements in the list. So any change in either ArrayList or Array will be reflected in other one too. Below is a simple program showing this behavior.

When we run above java program, it returns the following output.

As you can see that we changed the first element of ArrayList and second element of the Array. However, change is reflected in both ArrayList and Array and at the end, both have the same objects.

Java ArrayList to Array – Deep Copy

So if you want to convert ArrayList to Array and want them to be detached, then you will have to do a deep copy and write code for yourself. Below is a refactored code showing how to perform deep copy for converting ArrayList to Array.

Below is the output produced by the above application.

That’s all for java ArrayList to Array conversion using different methods.

Reference: Java ArrayList toArray API Doc

By admin

Leave a Reply