I have the following code that will sort Employees'sbased on their experience.
Employees's
I add 2 employees with different nameand the same experience. I expect set2 employees to work in the end , but I only get one.
name
experience
set
I also redefined equalsand hashcode. Can someone tell me why I get only one employee in the set.
equals
hashcode
Testing class
import java.util.Comparator; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.junit.Test; public class SetWithComparator { @Test public void testComparatorWithSet() { Comparator<Employee> comparator = (emp1, emp2) -> emp1.getYearOFExp().compareTo(emp2.getYearOFExp()); Set<Employee> empSet = new TreeSet<>(comparator); Employee e1 = new Employee(); e1.setName("Employee-1"); e1.setYearOFExp(12f); Employee e2 = new Employee(); e2.setName("Employee-2"); e2.setYearOFExp(12f); empSet.add(e1); empSet.add(e2); } }
Model class
class Employee { private String name; private Float yearOFExp; public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getYearOFExp() { return yearOFExp; } public void setYearOFExp(Float yearOFExp) { this.yearOFExp = yearOFExp; } @Override public boolean equals(Object obj) { if (obj instanceof Employee) { Employee e = (Employee) obj; return new EqualsBuilder().append(name, e.getName()).isEquals(); } else { return false; } } @Override public int hashCode() { return new HashCodeBuilder().append(name).toHashCode(); } }
a SortedSet Comparator , , . , , :
SortedSet
Comparator
Comparator<Employee> comparator = Comparator.comparing(Employee::getYearOFExp) .thenComparing(Employee::getName);
, , . , . , , , , , shouldnt, , , . equals hashCode.
hashCode
, , , .
equals. , Comparator.
, c S, , c.compare(e1, e2) == 0 e1.equals(e2) e1 e2 S., ( ). , ( ) c ( ), S. , c S, , set ( ) "". , set ( ) ( map), .
, c S, , c.compare(e1, e2) == 0 e1.equals(e2) e1 e2 S.
, ( ). , ( ) c ( ), S. , c S, , set ( ) "". , set ( ) ( map), .
, , Comparable ( ):
, a b, (! a.equals(b) & & a.compareTo(b) == 0) , , false ( ), a b .
: comparator.compare(e1, e2) - 0, e1.equals(e2) - false.
comparator.compare(e1, e2)
0
e1.equals(e2)
false
Source: https://habr.com/ru/post/1666693/More articles:Angular2 + webpack do not deploy robots.txt - angularSend iOS Push notification in php with .p8 file - phpWhat function is called when an application is deleted from the task manager - androidUnexpected HTTP / 1.x request: POST / 3 / device / XXXX - phpfullcalendar- unable to cache JSON response from AJAX call - jsonSimple jquery function not working - jqueryJSON channel caching Fullcalendar - javascriptglobal variables in JS vs local storage vs values ββin the DOM, which one will be more efficient? - javascriptWhy are Ruby-related types of types based on strings (line-typed)? - ruby ββ| fooobar.comSpring Boot 2 and Kotlin (with Maven) - springAll Articles