• Post Reply Bookmark Topic Watch Topic
  • New Topic

HashSet custom comparision. not working properly  RSS feed

pratik gaurav
Posts: 16
Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package one;
import java.util.*;
public class MyHashSet {

public static void main(String[] args) {
HashSet<Student> hs=new HashSet<Student>();
hs.add(new Student(16,"abc",80));
hs.add(new Student(32,"abc",80));
Iterator itr=hs.iterator();


class Student {
int marks;
String name;
int roll;
public Student(int marks,String name,int roll) {
public String toString(){
return marks+"\t"+name+"\t"+roll;
/*we know total number of buckets 16; and
and number i am passing are multiple of 16, hence modulo remainder is 0.
therefore bucket number 0;
Sir my biggest question is why this equlas method is not coming into action
when bucket number is same.
but when the marks is exactly same then only it's working.
but not when i'm explicitly trying to send it in the same bucket.
please take care of it.
public int hashCode(){
return marks;
/*i am comparing based on these roll number and name which will give us
* when it will return true element will not be added
* only added when returned false.*/
public boolean equals(Object obj){
Student stud=(Student)obj;
return (this.roll==stud.roll && this.name.equals(stud.name));
Campbell Ritchie
Posts: 56593
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use the code buttonand put your question in the text, not as comments.
The program behaves correctly, which is all you need to know. You do not need to explore the implementation details of another class.

But if you check the hash codes and find them different, you assume there is a correct overriding of hashCode (there is) and do not need to call equals(). You also assume there is a correct overriding of equals(), which there isn't. The equals method should complete normally for all types of Object, even though you have to look carefully for that in the equals documentation. It says,
for any non-null reference values x and y
You are not accepting any non‑null reference values. If you pass any other type, you will suffer an Exception.
You will also suffer an Exception if you pass null, and the documentation says it returns false.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!