Menu
Topics Index
...
`

Find Unique Names2512


If you need explanation Read this topic

If you need Answer Take test on this topic

Find Unique Names2512
What will be the output of the following program?
import java.util.*;
public class FindUniqueNames {
    public static void main(String[] args) {
        HashSet<Name> uniqueNames = new HashSet<Name>();
        p(uniqueNames, "kohli");
        p(uniqueNames, "Sachin");
        p(uniqueNames, "saCHIN");
        p(uniqueNames, "koHLi");
    }
    private static void p(Set<Name> uniqueNames, String name) {
        uniqueNames.add(new Name(name));
        System.out.print(uniqueNames.size() + " " + uniqueNames.contains(new Name(name)) + " ");
    }
}
class Name {
    String name;
    public Name(String name) { this.name = name; }
    public boolean equals(Object obj) {
        return name.equalsIgnoreCase(((Name) obj).name);
    }
    public String toString() { return name;    }
}

A. 1 false 2 false 3 false 4 false
B. 1 true 2 true 2 true 2 true
C. 1 true 2 true 3 true 4 true
D. Some other output
E. Compilation Error or Runtime Error
Topic: Other Advanced Topics 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 is c when it matches with name it results true

Posted by Bharath Yelchuri    2014-04-03 09:00:32


Ans is D.. first two elements vl be added uniqueNames with false. and then sachin vl in to uniqueNames but it already came in the hashSet so becomes true.. so the output is 1 false 2 false 3 true 4 true..

Posted by Om Prakash Om    2014-04-03 11:01:33


Ans is A:every time it give false every  because   we are checkng in contains method with another Obj..so it wl giv false..

Posted by Uday Kumar    2014-04-03 12:09:02


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

Posted by Merit Campus    2014-04-04 06:06:02


© meritcampus 2019

All Rights Reserved.

Open In App