Data lost from TreeSet when using Comparator

I have the following code that will sort Employees'sbased on their experience.

I add 2 employees with different nameand the same experience. I expect set2 employees to work in the end , but I only get one.

I also redefined equalsand hashcode. Can someone tell me why I get only one employee in the set.

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();
    }

}
+4
source share
2 answers

a SortedSet Comparator , , . , , :

Comparator<Employee> comparator = Comparator.comparing(Employee::getYearOFExp)
                                            .thenComparing(Employee::getName);

, , . , . , , , , , shouldnt, , , . equals hashCode.

, , , .

+3

equals. , Comparator.

, 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.

+8

Source: https://habr.com/ru/post/1666693/


All Articles