Your equals()
is calling the default Object
class's method, which compares the Objects's identity*, that is, p1==p2
, not its contents. This is the default equals
from Object
:
public boolean equals(Object obj) {
return (this == obj);
}
If you want to define your logic in order to decide if two Player
s are equal, you need to override:
equals()
method
hashCode()
method to honor the equals-hash contract
class Player {
private String firstName;
private String lastName;
private double score;
private double rating;
// ...
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, score, rating);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
Player other = (Player) obj;
return Objects.equals(firstName, other.firstName) && Objects.equals(lastName, other.lastName)
&& score == other.score && rating == other.rating;
}
// ...
}
Java SE 16
Java 16 Records feature helps you get rid of all this boilerplate code. Most of the ceremonial code mentioned above is automatically available to you with just the following declaration:
record Point(String firstName, String lastName, double score, double rating) { }
If you want to work with Collections:
- Implement
Comparable
-- this won't let you directly compare, but useful for collections
- Implement
Comparator
If you want to work with Collections, in order to be able to sort, for example, you could implement the Comparable
interface. This avoids breaking the equals and hashcode contract, which is pretty difficult to achieve manually.
As Holger comments (he's giving me some lessons today) use this when there's a numeric based ordering involved.
If not, you can use the Comparator
interface.
In this example I'm using Comparable:
class Player implements Comparable<Player>
{
@Override
public int compareTo(Player p2)
{
/* Allows returning : (0)-> this==p2 | (1)-> this>p2 | (-1)-> this<p2
Anyway, the meaning of 1 and -1 is up to you.
if (this.name.equals(p2.name) && ...)
return 0;
else if ...
return 1;
return -1; */
}
}
* Thanks to Henry Twist for pointing this out.