Topics Index

Convert list to array

If you need explanation Read this topic

If you need Answer Take test on this topic

Convert list to array
What will be the output of the following program?
import java.util.*;

public class CollectionToArray
    public static void main(String[] args)
        List list = new ArrayList();
        list.add("Hai ");
        list.add("programmer ");
        list.add("have ");
        list.add("a ");
        list.add("nice ");
        String[] copyOfArray = (String[]) list.toArray(new String[0]);

        for(int i = 0; i < copyOfArray.length; ++i)
            String contents = copyOfArray[i];

A. Hai programmer have a nice
B. Hai programmer have a nice day.
C. programmer have a nice day.
D. programmer have a nice
E. Compilation Error or Runtime Error
Topic: Java Collection Algorithms

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.


Here List is created by adding the String elements in it.List instance is created by assigning it the objct of ArrayList.

--After that list is converted to Array using toArray() function and assigned to copyofArray which is also array of Strings.

--The contents of this copyofarray are printed by using the for loop by running it till the length of array using "length" variable with copyofArray.

--Each element is assigned to "contents" variable and printed using system.out.print.

Posted by Mânïshå Mùlchåndânï    2014-12-29 12:21:30

Answer is B
Here we have created an instance of ArrayListand assigned it to the reference of List.

Next we are adding the elements into the list and each of these elements is added in consecutive locations of the array

Next, we are creating a duplicate copy of the array using toArray() method and this method returns an array containing all of the elements in this list in proper sequence.

The elemnts of this array are printed to the console by traversing the array element by element and printing them on to console

Posted by Shashanka Mogaliraju    2014-12-29 19:02:03

This dose is now closed and the winners are Mânïshå Mùlchåndânï,  for 'First Correct Comment', Sai Ram,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Uday Kumar. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2014-12-30 04:40:25

© meritcampus 2019

All Rights Reserved.

Open In App