Java Reference
In-Depth Information
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Person)) {
return false;
}
// id must be the same for two Persons to be equal
Person p = (Person) o;
if (this.id == p.getId()) {
return true;
}
return false;
}
@Override
public int hashCode() {
// A trivial implementaiton
return this.id;
}
@Override
public String toString() {
return "(" + id + ", " + name + ")";
}
}
You cannot add an object of the Person class in a SortedSet unless you also supply a Comparator object.
The following code will throw a ClassCastException :
Set<Person> persons = new TreeSet<>();
persons.add(new Person(1, "John"));
persons.add(new Person(2, "Donna"));
The following snippet of code creates a SortedSet of persons using a Comparator that sorts the persons using
their names:
SortedSet<Person> personsSortedByName = new TreeSet<>(Comparator.comparing(Person::getName));
 
Search WWH ::




Custom Search