User27854
User27854

Reputation: 884

Trouble with equals method

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;
}

Upvotes: 2

Views: 141

Answers (4)

Chamil
Chamil

Reputation: 803

 public boolean equals(Object cond)

and

 public boolean equals(Student cond) 

has two different method signatures

The first one, You are overriding the Object class's equals method. (Same signature as Object.equals

The second one you overload the method. with different signature.

to override, the method signature must be similar.

That is why equals(Object other) works.

Upvotes: 1

Hirak
Hirak

Reputation: 3649

No, they are not the same. In order for the equals to work properly, you need to override the method from superclass (Object). And the overridden method signature is

public boolean equals(Object cond){}

By doing this public boolean equals(Student test){} you are effectively overloading the method. Thus it is no longer the call back method and the equals method of Object is getting called.

Upvotes: 1

Pierre Rust
Pierre Rust

Reputation: 2504

The contains javadoc states

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

You must override equals(Object), in your example you define equals(Student), which is not used when calling list1.contains(.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213193

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.

Upvotes: 10

Related Questions