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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.