Menu
Topics Index
...
`

Collections Swapping


If you need explanation Read this topic

If you need Answer Take test on this topic

Collections Swapping
What will be the output of the following program?
import java.util.*;

public class Swapping
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        System.out.println(list);
        for(int element1 = 0; element1 < list.size(); element1++)
        {
            for(int element2 = 0; element2 < list.size(); element2++)
            {
                Collections.swap(list, element1, element2);
            }
        }
        System.out.println("After swapping");
        System.out.println(list);
    }
}

A. [1, 2, 3, 4, 5]
After swapping
[5, 2, 3, 4, 1]
B. [1, 2, 3, 4, 5]
After swapping
[5, 4, 3, 2, 1]
C. [1, 2, 3, 4, 5]
After swapping
[3, 4, 5, 1, 2]
D. Compilation Error 
E. 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.

C.is the answer. as first list is accordingly printed by assigned values and then is swapped using collections so c is answer.

Posted by Shabaaz Shaikz    2014-03-03 12:49:59


Ans is C since list takes 1 2 3 4 5 values and rearranged after swapping 3 4 5 1 2 by for loop

Posted by Bharath Yelchuri    2014-03-03 13:30:46


Ans is C

Posted by Vinay Jogu    2014-03-03 16:19:50


Congratulations Shabaaz Shaikz. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-03-04 04:22:09


© meritcampus 2019

All Rights Reserved.

Open In App