While working with ArrayList, there may be a need to get the actual array that holds the elements of the list. This conversion of ArrayList to array in Java may be required because-
- You have to pass the List to some third party method which takes array as parameter.
- For faster processing of certain operations.
Converting ArrayList to Array in Java by looping
Well there is always brute force approach to loop through the list, get the elements of the list using get method and assign them to array.
public class ConvertArray { public static void main(String[] args) { List<String> cityList = new ArrayList<String>(); cityList.add("Delhi"); cityList.add("Mumbai"); cityList.add("Bangalore"); cityList.add("Hyderabad"); cityList.add("Chennai"); // Create an array of the same size as list String cityArray[] = new String[cityList.size()]; // Loop through the list and assign values to array for(int i =0; i < cityList.size(); i++){ cityArray[i] = cityList.get(i); } //Displaying Array values for(String name : cityArray) { System.out.println("City : " + name); } } }
Output
City : Delhi City : Mumbai City : Bangalore City : Hyderabad City : Chennai
Better approach for converting ArrayList to Array in Java
There is another option provided by Collection interface itself. Within Collection interface there are two versions of toArray() method which can be used to convert ArrayList to array.
- Object[] toArray()
- <T> T[] toArray(T array[])
The first version returns an array of Object. The second version returns an array containing the elements of the same type as list. Normally we go with the second version because it returns the array of the same type as List.
Let's see the same example as above with the second version of toArray() to convert an ArrayList to array in Java.
public class ConvertArray { public static void main(String[] args) { List<String> cityList = new ArrayList<String>(); cityList.add("Delhi"); cityList.add("Mumbai"); cityList.add("Bangalore"); cityList.add("Hyderabad"); cityList.add("Chennai"); // Create an array of the same size as list String cityArray[] = new String[cityList.size()]; cityArray = cityList.toArray(cityArray); //Displaying Array values for(String name : cityArray) { System.out.println("City : " + name); } } }
So that's how we can get an array from ArrayList.
That's all for this topic How to Convert ArrayList to Array in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment