[Solved] I am new to programming and I can’t tell if this error is occurring because of my syntax


You are using equals method with your custom object Student.

You need to override it in your Student class. In your case, if you want to match all fields of s1 to s2, your implementation should go like this:

//Overriding equals
 public boolean equals(Object obj) 
  {
    if (this == obj) return true;
    if (obj == null) return false;
    if (this.getClass() != obj.getClass()) return false;
    Student that = (Student) obj;
    if (!this.name.equals(that.name)) return false;
    if (!this.ssn.equals(that.ssn)) return false;
    if (!this.gpa.equals(that.gpa)) return false;
    return true;
  }
}

Doing this will give you expected results when doing s1.equals(s2).

But, say for example if you try to add these same objects s1 and s2 to a Set, it will consider them as different. The reason being, the hashcode for both will be different.

So, when you override equals, you should also override the hashcode method.

A sample implementation for it, considering you have some Id field in your Student class is:

@Override
public int hashCode()
{
    final int PRIME = 31;
    int result = 1;
    result = PRIME * result + getId();
    return result;
}

You should use same fields to implement both equals and hashcode methods.

After doing this, your code should give you expected results.

Hope that helps!

1

solved I am new to programming and I can’t tell if this error is occurring because of my syntax