Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/how-to-override-equals-in-java
Question 174 / 297:  What is the expected output after compiling and running the following code?
import java.util.HashSet;

import java.util.Set;

public class Test{

public static void main(String[] args) {

Set<Foo> myFooSet = new HashSet<Foo>();

myFooSet.add(new Foo(2));

myFooSet.add(new Foo(1));

myFooSet.add(new Foo(3));

myFooSet.add(new Foo(3));

myFooSet.add(new Foo(2));

System.out.print(myFooSet.size());

}

}

class Foo {

Integer code;

Foo(Integer c) {

code = c;

}

public boolean equals(Foo f) {

return false;

}

public boolean equals(Object f) {

return true;

}

public int hashCode() {

return 17;

}

}

A  1
B  3
C  5
D  compilation error
<< First < Previous Next > Last >>
Explanation:

A Set collection doesn't allow for duplicates.

The process of inserting is done in two steps:

Step 1 : use the hashCode() to determine the bucket number (in this case it is 17 for all objects), so all objects are inserted in one bucket.

Step 2: use equals() method to check that there is no object already inserted in this bucket that is equal to the willing-to-insert object (and that's to avoid duplicity). Here is the trick, which equals() method is used in this case, the one with Foo parameter or with Object parameter. It is the one with Object parameter that is used, since it is the correct overriding for equals() method inherited from class Object. And since this equals() returns always true it means the set will insert only one element and rejects the others since they are equal to the already inserted element.

Exam Home Page
https://www.jobilize.com/java-certification-questions

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
Dravida Mahadeo-J...
Start Quiz
Madison Christian
Start Quiz
Copy and paste the following HTML code into your website or blog.
<iframe src="https://www.jobilize.com/embed/java-certification-questions" width="600" height="600" frameborder="0" marginwidth="0" marginheight="0" scrolling="yes" style="border:1px solid #CCC; border-width:1px 1px 0; margin-bottom:5px" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe>