Why do we convert ArrayList to array in Java?

Convert ArrayList to Array Java

When youre working with an ArrayList, you may encounter a situation where you want to convert it into an array, or vice versa. For instance, you may have a list of stocks in your portfolio stored in an array and want to convert it into an ArrayList.

In Java, the toArray() method is used to convert an ArrayList to an array, and the asList() method is used to convert a list to an ArrayList. This tutorial will discuss, with reference to examples, how to convert an ArrayList to an array and vice versa in Java.

Java Array and ArrayList

In Java, arrays are used to store a sequence of zero or more values. For instance, an array may store a list of candies sold at a candy store, or a list of orders that have been placed at a local cafe. Arrays can store any data type such as floats, booleans, and strings.

Heres an example of an array in Java:

String[] names = new String[5];

In this example, we have initialized an array called names which stores five string values.

Before you can use an array in Java, you need to declare its size. In addition, once you have declared the size of an array, it can be difficult to change it.

Thats where the ArrayList class comes in. ArrayList is an implementation of the Java List interface and allows developers to create resizable arrays. When you add or remove an object from an ArrayList, the capacity of the list is automatically changed to reflect the number of values that are stored in the list. In this tutorial, we will simply refer to the ArrayList class as a list.

» MORE: Exception Handling with Try Catch in Java

Heres an example of an ArrayList in Java:

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today
ArrayList<String> names = new ArrayList<>();

In the above example, we have declared an ArrayList called names which stores any number of string values.

Now that we know the basics of Java arrays and ArrayLists, we can explore how to convert data using these data types.

Convert List to Array

In Java, the list.toArray() method is used to convert a list to an array.

Suppose we have a list of stocks in our retirement portfolio stored in an ArrayList. We have decided that we want this to be stored in an array because we do not intend on adding new stocks to our retirement portfolio.

We could convert the list with our list of stocks to a Java array using this code:

import java.util.List; import java.util.Arrays; import java.util.ArrayList; class Main { public static void main(String[] args) { List<String> portfolio = new ArrayList<String>(); portfolio.add("BAM"); portfolio.add("GOOGL"); portfolio.add("SBUX"); String[] newPortfolio = new String[portfolio.size()]; portfolio.toArray(newPortfolio); System.out.println("Portfolio: " + Arrays.toString(newPortfolio)); } }

Our code returns:

Portfolio: [BAM, GOOGL, SBUX]

Lets break down our code. First, we import three libraries into our program, which are: List, Arrays, and ArrayList. The List library allows us to work with the Java List interface, the ArrayList library allows us to work with ArrayLists, and Arrays allows us to use the toString() method to print our array to the console.

Why do we convert ArrayList to array in Java?
Find Your Bootcamp Match
  • Career Karma matches you with top tech bootcamps
  • Get exclusive scholarships and prep courses
Please enter a valid phone number
Get Matched
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Then we declare an ArrayList called portfolio which stores string values. We then use the add() method to add three values to our portfolio: BAM, GOOGL, and SBUX.

On the next line of our code, we create an array called newPortfolio and initialize the array and the size of the array. We set the capacity of the newPortfolio string array the number of values it can hold to be equal to the length of the portfolio array. So, in this case, the newPortfolio array will be capable of holding three values.

» MORE: Java Compare Strings: A Step-By-Step Guide

Next, we use the toArray() method to convert our portfolio ArrayList to an array and assign the newPortfolio array the values stored within the variable portfolio. We then use Arrays.toString() to convert the newPortfolio variable to a readable string of values. Finally, we print out the message Portfolio: , followed by the value returned by Arrays.toString(), to the console.

Convert Array to List

The asList() method is used to convert an array to an ArrayList in Java.

Lets return to the retirement portfolio example from earlier. Suppose we had an array of stocks in our retirement portfolio which we want to convert into an ArrayList. We could do so using this code:

import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { String[] portfolio = {"BAM", "GOOGL", "SBUX"}; List<String> newPortfolio = Arrays.asList(portfolio); System.out.println("New portfolio: " + newPortfolio); } }

Our code returns:

New portfolio: [BAM, GOOGL, SBUX]

In this example, we have used asList() to convert our retirement portfolio array called portfolio to a list. Lets break down our code.

First, we import the Arrays and List packages, which contain the methods we need to convert our array to a list. Then we declare a variable called portfolio which contains an array of the stocks in our retirement portfolio.

On the next line, we use the Arrays.asList() method to convert the contents of the portfolio array to a list. We then assign the new list to the variable newPortfolio. Finally, we print out the message New portfolio: , followed by the contents of the newPortfolio array

Conclusion

The Java toArray() method is used to convert a list to an array, and the asList() method is used to convert an array to a list.

» MORE: Java Substring: A How-To Guide

This tutorial discussed, with reference to examples, how to convert an ArrayList to array and an array to an ArrayList in Java. In addition, this tutorial discussed the main difference between the ArrayList class and the array data type. Youre now ready to start converting ArrayLists to arrays, and vice versa, like a professional Java coder!

Why do we convert ArrayList to array in Java?
Why do we convert ArrayList to array in Java?

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

Find Your Bootcamp Match
Rate this Article


About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.


What's Next?

Why do we convert ArrayList to array in Java?
Why do we convert ArrayList to array in Java?
Want to take action?

Get matched with top bootcamps

Why do we convert ArrayList to array in Java?
Why do we convert ArrayList to array in Java?
Want to dive deeper?

Ask a question to our community

Why do we convert ArrayList to array in Java?
Why do we convert ArrayList to array in Java?
Want to explore tech careers?

Take our careers quiz