Convert ArrayList to Array

In this tutorial we will see, How can you convert ArrayList to Array or How can you perform the conversion of ArrayList in Java. First, We will see how can we convert the ArrayList into Array then we will see how can we convert the Array into ArrayList.

 

Convert ArrayList to Array:

In ArrayList class we have inbuilt method toArray() , using this we can convert the ArrayList into Array. We can also do this in Manual way using get() method. We can traverse the ArrayList and use get() method add each element one by one into an Array but this is the tedious and time-consuming way.

Let’s see how can we convert the ArrayList into Array using toArray() method of ArrayList class.

Output:

15
20
Test
100
123

 

Note in the above example toArray(new String[elements.size()]), returns an String array of the elements in the ArrayList elements.

Here first we are creating the ArrayList of elements then we are adding the elements in the ArrayList. After this we have created an Array named sample and copied the arrayList into the sample Array and print the elements of the sample array.

So like we can convert the ArrayList into Array in Java.

 

Convert Array to ArrayList

There are many ways to convert Array to ArrayList. First is manual way, you can transfer the array and add the each element of the array to ArrayList manually using add() method of the arrayList.

Second, we can use, Arrays.asList() method to convert the Array into ArrayList.

Output:

[London, Banglore, Bangkok, Dubai, Istanbul, New York]

 

Using this we can convert the Array into ArrayList. In this example first we have created the Array and then we converted the Array into ArrayList and print the ArrayList.

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply