June 2018
Beginner
722 pages
18h 47m
English
Now, let's implement the equals() method:
class PersonWithEquals{ private int age; private String name; private String hairstyle; public PersonWithEquals(int age, String name, String hairstyle) { this.age = age; this.name = name;
this.hairstyle = hairstyle; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PersonWithEquals person = (PersonWithEquals) o; return age == person.age && Objects.equals(name, person.name); }}
Notice that, while establishing the objects' equality, we ignore the hairstyle field. Another aspect that requires comments is the use of the equals() method of the java.utils.Objects class. Here is its implementation: ...
Read now
Unlock full access