Menu
Question Index
...

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.toUpperCase().hashCode(); }
    public boolean equals(Object obj) {
        return name.equalsIgnoreCase(((Name) obj).name);
    }
    public String toString() { return name;    }
}


1 false 2 false 3 false 4 false
1 true 2 true 2 true 2 true
1 true 2 true 3 true 4 true
Some other output
Compilation Error or Runtime Error

Doubts

Problems

Topic: Other Advanced Topics In Java

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App