Menu
Topics Index
...
`

Collections Output


If you need explanation Read this topic

If you need Answer Take test on this topic

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

public class CollectionsTest {

    public static void main(String[] args) {
        List<A> l = new ArrayList<A>();
        l.add(new A(5, 4));
        l.add(l.get(0));
        l.add(new A(6, 0));
        l.add(new A(5, 4));
        l.add(new A(6));
        Set<A> s = new HashSet<A>();
        s.addAll(l);
        System.out.print("l = " + l.size() + " s = " + s.size());
    }
}

class A {
    int i, j;
    public A(int i, int j) { this.i = i; this.j = j; }
    public A(int i) { this.i = i; }
}

A. l = 5 s = 4
B. l = 5 s = 5
C. l = 3 s = 3
D. l = 5 s = 3
E. Compilation Error or Runtime Error
Topic: HashSet Class In Java

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 : b
l= 5 s= 5
in l arraylist 5 items are added....so length of the list l is 5....
then s hash set create by l....
so its content size equal to list l
..
so output is..
l= 5  s=5

Posted by Ananda Kumar    2014-04-09 09:00:17


Here add() method adds specified objects to the ArrayList {we have added 5 objects and the second object being added is the same as the first one ---> l.add(l.get(0)}. We are then adding all of the elements of ArrayList to the HashSet using addAll() method. But HashSet doesn't allow duplicate values. So the SOP statement prints out 5 as the size of ArrayList and 4 as the size of the HashSet. So the answer is A.

Posted by Shaileshwar Sharma    2014-04-09 09:41:56


A is correct answet

Posted by Supriya Chowdary    2014-04-09 13:32:13


No winner for this dose. Correct option is 'A' :(. Shaileshwar Sharma was already won in this week.

Posted by Merit Campus    2014-04-10 03:58:39


© meritcampus 2019

All Rights Reserved.

Open In App