Menu
Topics Index
...
`

Add And Remove From Collections


If you need explanation Read this topic

If you need Answer Take test on this topic

Add And Remove From Collections
What will be the output of the following program?
import java.util.*;
public class AddAndRemoveCollection {
    public static void main(String[] args) {
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(4);     p(ids);
        ids.add(3);
        ids.add(2);     p(ids);
        ids.remove(0);     p(ids);
        ids.add(1);     p(ids);
        ids.remove(new Integer(0));     p(ids);
        ids.add(1, 6);    p(ids);
        ids.remove(new Integer(6));    p(ids);
        ids.remove(2);    p(ids);
    }
    private static void p(List<Integer> ids) {
        System.out.print(ids);
    }
}

A. [4][4, 3, 2][4, 3, 2][4, 3, 2, 1][4, 3, 2, 1][4, 6, 3, 2, 1][4, 3, 2, 1][4, 3, 1]
B. [4][4, 3, 2][3, 2][3, 2, 1][2, 1][2, 6, 1][2, 1][2]
C. [4][4, 3, 2][3, 2][3, 2, 1][3, 2, 1][3, 6, 2, 1][3, 2, 1][3, 2]
D. Compilation Error
E. Runtime Error
Topic: Java ArrayList

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.

Ans is C. First 4 is added to the list and the list is printed. Next 3 and 2 are added. Next remove(0) removes the value at index 0 i.e., 4 since object 0 is not available it treats 0 as index. next 1 is added. remove(new Integer(0)) looks for 0 object since it is not there nothing happens and so on..

Posted by Nikhil Sulibhavi    2014-05-14 13:10:07


Ans is E bcoz when it reaches remove(new Integer(6)) it is out of the ArrayList index(at that time we have only 4 element in list), so we wil get Runtime Error as Index Out of bound Exception.

Posted by Nagendra Reddy    2014-05-14 15:07:43


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

Posted by Merit Campus    2014-05-15 04:32:53


© meritcampus 2019

All Rights Reserved.

Open In App