Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

HashCode and equals problem

PremSep 5 2011 — edited Sep 6 2011
Hi I am implementing hashcode and equals method to avoid duplicates in Set collection. I successfully did it but confused ..

following is code snippet :


package TestCollection;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.SortedSet;
import java.util.TreeSet;

class Student
{

private int id;
private String fname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}



@Override
public int hashCode() {

System.out.println("hashcode -->"+this.id+"--"+this.fname);
return this.id;
}

@Override
public boolean equals(Object o) {
System.out.println("equals -->"+((Student)o).getFname());
boolean bool = false;
if(this.id == ((Student)o).getId())
bool = true;
System.out.println("#############################"+this.getFname());
return bool;
}

@Override
public String toString() {
// TODO Auto-generated method stub
String s=""+this.id+" "+this.fname;
return s;
}
}

public class TestSetToAvoidDuplicateOfUserDefinedClass
{

public static void main(String[] args) {

HashSet tSet=new HashSet();
Student s1=new Student();

s1.setId(1);
s1.setFname("abc");

Student s2=new Student();
s2.setId(1);
s2.setFname("xyz");

Student s3=new Student();
s3.setId(2);
s3.setFname("abc");

Student s4=new Student();
s4.setId(3);
s4.setFname("lmn");


tSet.add(s1);
tSet.add(s2);
tSet.add(s3);
tSet.add(s4);





for(Object o:tSet)
{
System.out.println("-->"+o);
}




}


}

while adding equals method is being called only once when is s2 is about to add. For others it is not being called .. Could you please elaborate this kind of behavior...
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 4 2011
Added on Sep 5 2011
9 comments
538 views