Do I need to define my own hash and equal method?

If I need to use InfoName

both key

for HashMap

, I need to define my own method hashCode()

and equals()

? I think this is not necessary, as a String variable name

will be enough for each object to be InfoName

different.

public class InfoName {
    enum Type {
        company, product;
    }

    public String name;
    public Type type;

    public InfoName(String name, Type type) {
        this.name = name;
        this.type = type;
    }
}

      

+3


source to share


3 answers


the String variable "name" will suffice to make each InfoName object different

If you want to use name

in InfoName

, just put String

type name

as key

as it already overrides equals()

and hashCode()

.



OR

You need to override equals()

it hashCode()

in the class as well InfoName

, otherwise how the JVM knows which attribute / criteria you are using to check for hash and equality.

+2


source


If you have an InfoName key, you need to override both. You have something like

public class Test {
    enum Type {
        company, product;
    }

    public String name;
    public Type type;

    public Test(String name, Type type) {
        this.name = name;
        this.type = type;
    }

    @Override
    public boolean equals(Object o) {//or do what you like
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Test test = (Test) o;

        if (!name.equals(test.name)) return false;
        if (type != test.type) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + type.hashCode();
        return result;
    }
}

      



Basically your editor provides hashcode and equals override functions. Look here Why do I need to override equals and hashCode methods in Java? enter link description here

0


source


I think this is not necessary, as the String variable "name" will suffice for each InfoName object to be different.

I would recommend not using it name

as a hash key because it seems like a bad candidate. I mean, is it possible to have multiple objects with the same product name? In this case, you will have a lot of collisions.

0


source







All Articles