Wednesday, December 21, 2016

How to convert ArrayList to Array In Java

In this post we will learn how to convert ArrayList to Array in Java. I am sharing two methods of converting ArrayList to Array. In Java ArrayList is one of the important class in Collection Framework. It represents growable collection of objects whereas Array is fixed length collection of objects.In previous post we were discussed about how to get IP address of any website,today we will discuss about conversation ArrayList to Array. 

Method 1:  To convert ArrayList to Array The following method we used

Object[] toArray() method.

Syntax: public Object[] toArray()

In the above toArray() method is existed in interface collection and interface list. It returns an array containing all of the  elements in this list in correct order. 

Why need to convert ArrayList to Array:
There might be a scenarios where the output of a java API method is in ArrayList format and our business requirements is expecting an array,therefore we need to conversion AarryList ot Array.

Consider the following example Converstion using toArray() method:

import java.util.*;
class ArrayListToArray
{
public static void main(String args[])
{
List  al=new ArrayList();
al.add("learn");
al.add("java");
al.add("bylucky");
String[] arrayString=new String[al.size()];
al.toArray(arrayString);
for(String element: arrayString)
{
System.out.println(element);
}
}
}


Output:






In the above example we have a list of Strings of ArrayList values. Then convert the collection to an array using toArray() method of the List. toArray() method returns an array of type object.we need to typecast it to String before using as String objects.If we do not typecast we get compile time error.

In another method is manual method to convert ArrayList to Array using get() method as follows:

We can use get() method if you don not want use java bulit-in method toArray(). Sometimes Interviewer may ask you without using toArray() method how can you convert ArrayList to Array. By that time manual method is very useful.

Consider the following example Conversation ArryList to Array using get() method:

import java.util.*;
class ArrayListToArray
{
public static void main(String args[])
{
List<Integer>  al=new ArrayList<Integer>();

al.add(10);
al.add(20);
al.add(30);
al.add(40);
al.add(50);
Integer[] arr=new Integer[al.size()];
for(int i=0;i<al.size();i++)
arr[i]=al.get(i);
for(Integer element:arr)
System.out.println(element);

}


Output:










Let me know if any other methods used to convert ArryList to Array and Keep follow me for latest updates.

 

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...