Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/how-the-set-collection-allows-no-duplicates-in-java
Question 202 / 297:  In this program, the set humans allows for objects of type Human with the same age to be inserted. What can be done to make the set reject any Human object with value age equals to age value for an already inserted human object?
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));

}

}

class Human {

Integer age;

public Human(int age) {

this.age = age;

}

}

A  only override method equals() in Human as follows: public boolean equals(Object h) { return
this.age==((Human)h).age; }
B  only override method hashCode() in Human as follows: public int hashCode(){ return 17; }
C  must override both methods hashCode() and equals() as illustrated in the above answers
<< 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 is not equal to any other Human object.

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
Brooke Delaney
Start Exam
Rachel Woolard
Start Quiz
Savannah Parrish
Start Exam
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>