datatype[] isArray;
Where datatype is any primitive data type like int, float, long, or even String. You can also place the brackets after the declaration like so:
datatype isArray[];
So how do we take this static array with a set number of elements and convert it to an ArrayList? Well, first, let’s look at what an ArrayList is.
The ArrayList
An ArrayList may have a similar name to an Array but it is handled completely differently. That’s because an ArrayList doesn’t extend the Container class, it extends the List class. And that means that everything gets handled differently. For one thing, because it is a List, you can manipulate it differently. You can increase or decrease the size of the ArrayList using add(element), which places the element at the end of the List and increases the size by one if necessary. Or you can use trimToSize() which removes any empty indices at the end and trims the ArrayList to its current size. So you can see that there are a few advantages to using an ArrayList instead of just an array. Next we’re going to show you two methods to convert from an Array to an ArrayList and how to move back if you need to.Moving from Array to ArrayList and ArrayList to Array in Java
So, let’s say that you have written a program to keep an inventory of how many nuts and bolts your company has on hand for repairing cat trees. For years, you have only needed 30 different types of them, so it’s been easy to just use an array to keep track. But now you have a new client who requires you to stock an additional 5 types. How can you change your program and keep all of your data, AND prevent yourself from having to do this again when you pick up another client? That’s right! An ArrayList! So how do you convert a Java Array to an ArrayList? There are three methods. Using the .asList() method Java arrays have a great tool that you can see when you look at the API called .asList(). So you could just write in this:
boltInventory.asList(bolts);
The problem with this method is that it doesn’t create a true ArrayList. What it does is create a List that is fixed in size and unchangeable. So you still can’t change the size in a dynamic way. Trying to add or remove elements will cause an exception. So while this does have its uses, it isn’t a true conversion. But we can use this.
Using the .asList() as a an Argument
This is the second way to convert an array to list in Java. Because the .asList() method creates a List, we can use that to pass a reference to our actual ArrayList.
Here is how to initialize an ArrayList:
ArrayList<Integer> boltsInventory = new ArrayList<Integer>();
This will create an ArrayList that has ten empty cells. However, the () at the end can be used to pass an argument to fill the ArrayList. So combining with the .asList method, you have:
ArrayList<Integer> boltsInventory = new ArrayList<Integer>(Arrays.asList(bolts));
This passes the List created by the .asList() method into the ArrayList, so now you can dynamically manipulate it as you need.
Using the Collections.addAll() method
Another way to convert an Array to an ArrayList in Java is to use this method. It passes the contents of the Array to the ArrayList.
The generic syntax for this method is:
Collections.addAll(c, T);
Where c is the destination and T is what is being passed. So for our example, the syntax would look like this:
ArrayList<Integer> boltsInventory = new ArrayList<Integer>():
Collections.addAll(boltsInventory, bolts);
This will pass the entire contents of the Array bolts to the new ArrayList.
Converting an ArrayList to an Array
There may be a time when you need to convert an ArrayList to an Array in Java. If you do, the ArrayList has a method .toArray(a), where a is the destination. So for our example, the syntax would be:
Integer boltsInventoryArray[] = new Integer{boltsInventory.size()];
// this ensures the newly created array is of the same size as the ArrayList
boltsInventoryArray = boltsInventory.toArray(boltsInventoryArray);
When you change a list to array in Java like this, you are creating a deep copy. That is, all references to the Array are different from the references to the ArrayList. So you can manipulate the data in the Array without changing the data stored in the ArrayList. It is useful to convert a java list to an array when you need to test data.
So, you've learned how to initialize arrays and convert them to ArrayLists in Java. Great job! But wait, there's one more important piece of the puzzle you need to know: the toArray(T[])
method. This method is essential for safely converting an ArrayList
back to a typed array. Let's break it down step-by-step!
What is toArray(T[]) and Why Use It?
Java’s ArrayList
class provides two toArray()
methods:
Object[] toArray()
T[] toArray(T[] a)
Wait, two methods? Yep! And here's why the second one, toArray(T[])
, is super important:
Type Safety
The basic toArray()
method returns an Object[]
, meaning you'd have to manually cast it back to your desired type. Yikes! That could lead to ClassCastException
. The toArray(T[])
method, on the other hand, keeps things safe by returning a properly typed array. No risky casting needed!
Practical Examples of toArray(T[]) in Action
Let’s see how this works in practice. Ready for some hands-on action? Let’s go!
Example 1: Converting an ArrayList to a Typed Array
import java.util.ArrayList;
import java.util.List;
public class ToArrayExample {
public static void main(String[] args) {
List fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Convert ArrayList to String array using toArray(T[])
String[] fruitArray = fruits.toArray(new String[0]);
// Print the array
for (String fruit : fruitArray) {
System.out.println(fruit);
}
}
}
Output:
Apple
Banana
Cherry
Nice and easy! Notice how we didn’t have to cast anything? That’s type safety in action!
Example 2: Using toArray(T[])
with Integers
import java.util.ArrayList;
import java.util.List;
public class IntegerArrayExample {
public static void main(String[] args) {
List numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
// Convert ArrayList to Integer array
Integer[] numberArray = numbers.toArray(new Integer[0]);
for (Integer num : numberArray) {
System.out.println(num);
}
}
}
Output:
1
2
3
Same idea, just with numbers! See how versatile this method is?
Comparing toArray() vs. toArray(T[])
Still wondering why we don’t just use the basic toArray()
? Let’s compare the two.
Example: Using toArray()
List items = new ArrayList<>();
items.add("Pen");
items.add("Notebook");
// Using basic toArray()
Object[] objectArray = items.toArray();
for (Object obj : objectArray) {
String item = (String) obj; // Must cast to String
System.out.println(item);
}
Yikes! That manual casting is risky. A wrong cast could cause a ClassCastException
.
Example: Using toArray(T[])
// Using toArray(T[])
String[] stringArray = items.toArray(new String[0]);
for (String item : stringArray) {
System.out.println(item);
}
Much better, right? No casting needed, and your IDE can even help with autocompletion!
Quick Comparison Table
Method | Return Type | Type Safety | Use Case |
---|---|---|---|
toArray() |
Object[] |
No (requires casting) | Quick conversions when type safety isn’t a concern |
toArray(T[]) |
T[] |
Yes (no casting needed) | Type-safe conversions to a specific array type |
GO TO FULL VERSION