- Inoder to convert arraylist to array normally we will try to iterate arraylist using loop and get each element and put it in an array.
- But you know we have a predefined method in arraylist which convert list to array of elements in sequence order.
- toArray() method inside arraylist class.
- public <T> T[] toArray(T[] a) { }
- Lets see a java program on how to convert arraylist to array.
Program #1: Java example program to covert arraylist to array using toArray() method
- package arraysinterview;
- import java.util.ArrayList;
- import java.util.List;
- public class ArrayListTOArray {
- public static void main(String[] args) {
- List<String> list = new ArrayList<String>();
- list.add("array");
- list.add("arraylist");
- list.add("convertion");
- list.add("javaprogram");
- String [] str = list.toArray(new String[list.size()]);
- for (int i = 0; i < str.length; i++) {
- System.out.println(str[i]);
- }
- }
- }
Output:
- array
- arraylist
- convertion
- javaprogram
Program #2: Java example program to covert Integer arraylist to int array using toArray() method
- In this case toArray() method gives Integer array so we need to convert again Integer array to int array.
- package arraysinterview;
- import java.util.ArrayList;
- import java.util.List;
- public class ArrayListTOArray {
- public static void main(String[] args) {
- List<Integer> list = new ArrayList<Integer>();
- list.add(10);
- list.add(20);
- list.add(30);
- list.add(40);
- list.add(50);
- Object[] integers = list.toArray();
- int[] intarray = new int[integers.length];
- int i = 0;
- for (Object n : integers) {
- intarray[i++] = (Integer) n;
- System.out.println(i);
- }
- }
- }
Output:
- 1
- 2
- 3
- 4
- 5
when we need to convert arraylist to array
ReplyDelete