Menu
Topics Index
...
`

Delete Elements From List


If you need explanation Read this topic

If you need Answer Take test on this topic

Delete Elements From List
What will be the output of the following program?
import java.util.*;
public class DeleteElementsFromList {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(3); list.add(10); list.add(1); list.add(2);
        list.add(7); list.add(0); list.add(5);
        print(list.remove(2));
        print(list.remove((Integer) 7));
        print(list.remove(2));
        print(list.remove(new Integer(7)));
        print(list.remove(0));
        print(list.remove(new Integer(10)));
        print(list.size());
    }

    public static void print(int value)
    {
        System.out.print(value + " ");
    }

    public static void print(boolean value)
    {
        System.out.print(value ? "X " : "Y ");
    }
}

A. X 1 Y 2 2 X 3
B. 1 X 2 Y 3 X 2
C. X X X Y X X X
D. Some other output
E. Compilation Error or 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 B..here we have the AL Concept
AL is Advanced version of the Array where arrays are fixed in the size and arrays can store homogeneous elements where as AL are Growble in size and can store heterogeneous elements and AL can allow the null insertion and allows Duplicate elements and insertion order is preserved and AL implements RandomAccess interface

Execution:
here we create the AL with the Integer so it will store only Integer objects in it..using the add() we added the 3,10,1,2,7,0,5..all these are primitives than autoboxing will perform which converts into Primitives into Objects..next we are calling the remove method by passing 2 so it will remove the object at location 2 which is 1..next we are calling the remove with the Integer Object so it will remove and returns true if it contains otherwise it will return false..so 7 is there so it will remove than will return true so it will print x using ternary next passing the 2 so it will remove the value at the location 2..at location we have 2..next calling object 7 which is not present so it will remove false so we are printing the y similar to other calls also..finally we have the 2 elements so size is 2

Posted by Uday Kumar    2015-02-16 16:12:56


This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment', Uday Kumar,  for 'Best Comment' and Uday Kumar for the 'Popular Comment'. The 'lucky liker' is Phan Sovan Narith. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2015-02-17 05:00:34


© meritcampus 2019

All Rights Reserved.

Open In App