-1

lets say I have a Employee-class with Instant- and Id-Attribute:

public class Employee implements Comparable<Employee> {

    private Instant workEnd;
    private Integer id;
    private String name;

    public Instant getWorkEnd() {
        return workEnd;
    }

    public void setWorkEnd(Instant workEnd) {
        this.workEnd = workEnd;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Employee employee) {

        int workEndCompare = getWorkEnd().compareTo(employee.getWorkEnd());
        int idCompare = getId().compareTo(employee.getId());

        if (workEndCompare == 0) {
            return idCompare;
        } else {
            return workEndCompare;
        }
    }

    @Override
    public String toString() {
        return String.format("{Date: %s,Number: %d}", getWorkEnd(), getId());
    }
}

As you can see each Employee-Object sorts dependent on workEnd and id.

Now I want to put these Employee-Objects as Keys in a HashMap. But I want that the HashMap replaces each Key-Employee with the put()-method if the attributes workend and id are equal. Thta means I want the normal behaviour of a HashMap but with own custom Objects as Mapkeys.

How I manage that? By implementing the equals-method?

I tried something like that, but it does not work:

@Override
public boolean equals(Object obj) {
    if (obj instanceof Employee) {
        Employee employee = (Employee) obj;
        int workEndCompare = getWorkEnd().compareTo(employee.getWorkEnd());
        int idCompare = getId().compareTo(employee.getId());

        if ((idCompare + workEndCompare) == 0) {
            return true;
        } else {
            return false;
        }

    } else {
        return super.equals(obj);
    }
}
user3133542
  • 1,695
  • 4
  • 21
  • 42

1 Answers1

2

When you implement the equals method you also need to implement the hashcode method too.

There is something called the hashcode - equals contract, both need to be implemented for your hashmap to work,

The answer here explains it well.

Community
  • 1
  • 1
Ash
  • 2,562
  • 11
  • 31