Trouble with equals method

User27854

I have created a class called student which has an equals method as shown below. My problem is this.

I create an instance of student class and add it to ArrayList, Now I want to check weather the list contains a duplicate of student object. When i try this with the below equals function its giving wrong result.

for eg.

    Student stud1= new Student(101,"Student1");
    Student stud5= new Student(105,"Student5");
    Student stud6= new Student(105,"Student5");
    list1.add(stud1);
    list1.add(stud5);
    System.out.println(list1.contains( new Student(105,"Student5")));// outputting false



class Student{
int sid;
String sname;

public Student(int sid,String sname){
    this.sid=sid;
    this.sname=sname;
}

public String toString(){
    return ""+this.sid;
}



public boolean equals(Student test){
    return  this.sid==test.sid; 
}

}

but when I replace the equals function with the one below its giving a correct result.. Why is that? Technically there is no difference right? Could you please help me as how is the JVM looking at the code..

    public boolean equals(Object cond){
    if(cond instanceof Student){
        Student test = (Student) cond;
        return test.sid==this.sid;
    }
    return false;
}
Rohit Jain

The first equals(Student) method doesn't override the Object#equals(Object) method. Hence with that, the list.contains(Student) method will invoke the default Object#equals() method, and which compares the references using ==. So, for two different objects, it will return false.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related