Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/inserting-into-a-hashset-in-java
Question 201 / 297:  What is the result of compiling and running the following code?
import java.util.HashSet;

import java.util.Set;

public class Test{

public static void main(String[] args) {

Set<Human> humans = new HashSet<Human>();

humans.add(new Human(13));

humans.add(new Human(33));

humans.add(new Human(21));

humans.add(new Human(21));

System.out.print(humans.size()+" ");

System.out.print(humans);

}

}

class Human implements Comparable<Human> {

Integer age;

public Human(int age) {

this.age = age;

}

public int compareTo(Human h) {

return h.age.compareTo(this.age);

}

public String toString() {

return ""+this.age;

}

}

A  4 [33, 21, 13, 21]
B  3 [21, 33, 13]
C  compilation error
D  exception is thrown at run time
<< First < Previous Next > Last >>
Explanation:

A set depends on two methods to determine if the willing to insert object is already inserted or not. The two methods are hashCode() and equals().

The hashCode() determines the bucket number, while equals() determines if the one of the objects already inserted in the bucket is equal to the willing to insert object. In this case Human doesn't override hashCode() neither equals(). Which means every object of type Human has a unique hashCode and it is not equal to any other Human object. Therefore the four Human objects will be inserted in the set.

To make Set accepts no duplicates in this example, then override hashCode() and equals() in Human, as for example as following:

public boolean equals(Object h) {

return this.age==((Human)h).age;

}

public int hashCode(){

return 17;

}

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

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
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>