Java OCA OCP Practice Question 2406

Question

What is the output of the following code? (Choose all that apply.)

import java.util.*;
public class Main {
    public static void main(String args[]) {
        Person p1 = new Person("A");
        Person p2 = new Person("B");
         Person p3 = new Person("C");
         Person p4 = new Person("C");
         HashSet<Person> set = new HashSet<>();
         set.add(p1);//w w w .j av a2 s.c  o m
         set.add(p2);
         set.add(p3);
         set.add(p4);
         System.out.println(set.size());
     }
 }

 class Person {
     String name;
     Person(String name) {
         this.name = name;
     }
     public int hashCode() {
         return 20;
     }
     public boolean equals(Object obj) {
         return true;
     }
 }
  • a 0
  • b 1
  • c 2
  • d 3
  • e 4
  • f Compilation error
  • g Runtime exception


b

Note

Method HashSet() uses method hashCode() to determine an appropriate bucket for its element.

If it adds a new element to a bucket that already contains an element, HashSet calls equals on the elements to determine whether they're equal.

HashSet doesn't allow duplicate elements.

When it adds a Person object, the same hash Code value makes it land in the same bucket.

Calling the equals() method returns true, signaling that an attempt is being made to add a duplicate object, which isn't allowed by HashSet.




PreviousNext

Related