How To Convert An ArrayList to Array In Java
In many cases, you will have to convert an ArrayList to Array in Java. There is a most popular way to do is “Creating an object and use a for loop just like the below code”
Object[] objects = al.toArray();
// Printing array of objects
for
(Object obj : objects)
System.out.print(obj +
" "
);
Finding an ArrayList in Java is Empty or Not
But here we will learn a very simple to understand method.
Below is the java code to convert an ArrayList to Array in Java.
import java.util.ArrayList; public class Convert { public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>(); list.add("CodeSpeedy"); list.add("ArrayList"); list.add("Java"); String[] newstring=list.toArray(new String[list.size()]); for(int i=0;i<list.size();i++) { System.out.println(newstring[i]); } } }
Output:
run: CodeSpeedy ArrayList Java BUILD SUCCESSFUL (total time: 0 seconds)
How to Increase and Decrease Current Capacity (Size) of ArrayList in Java
Explanation:
We just created an ArrayList first
ArrayList<String> list=new ArrayList<String>();
Then we added String values in our list
list.add("CodeSpeedy"); list.add("ArrayList"); list.add("Java");
Next, we created a String and named it newstring
String[] newstring=list.toArray(new String[list.size()]);
It is the main part. We used toArraymethod to convert our ArrayList to Array.
for(int i=0;i<list.size();i++) { System.out.println(newstring[i]); }
By using string index we can print the strings one by one with the above code.
We initialized “i” with zero. Because array index starts with zero and in each iteration of our for loop we will print the next element in our string till the value of “i” reaches the last element of the array.
Leave a Reply