Menu
Topics Index
...
`

Find Unique Names2513


If you need explanation Read this topic

If you need Answer Take test on this topic

Find Unique Names2513
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 int hashCode() {    return name.hashCode(); }
    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 .. here we are typecasting the objects into Name class and comparing.. so all becomes true and size vl be incremtd everytime..

Posted by Om Prakash Om    2014-03-26 13:09:10


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

Posted by Merit Campus    2014-03-27 04:21:22


© meritcampus 2019

All Rights Reserved.

Open In App