Java – should I override the hashcode () of the collection?

Given that I have a number of courses that cover a variety of areas:

class MyClass {
    private String s;
    private MySecondClass c;
    private Collection<someInterface> coll;
    // ...

    @Override public int hashCode() {
        // ????
    }
}

Moreover, I do have all kinds of objects, and I want to store them in HashMap To do this, I need to have the hashcode () of MyClass

>I will have to recursively enter all fields and corresponding parent classes to ensure that they implement hashcode () correctly, because otherwise, hashcode () of MyClass may not consider some values Is this correct? > What should I do with this series? Can I always rely on the hashcode () method? Does it take into account all possible child values in my someinterface object?

Here I open the second question about the practical problem of unique ID objects: how do I generate an (almost) unique hash ID for objects?

Clarification:

If any value in the Coll of one of the objects changes, the MyClass hashcode () of the two objects will certainly be different If all fields of two objects store the same value, hashcode should only return the same value Basically, do some time - consuming calculations on the MyClass object If the calculation has been completed with exactly the same value in the previous period of time, I think there is extra time To do this, if the results are already available, I want to view HashMap

Therefore, I use hashcode of MyClass as the key in HashMap The value (calculation result) will be different, such as integer (Simplified)

Won't it depend on the collection type stored in the coll? Although I don't think ordering is important, No

The response you get from this website is gorgeous Thank you

Yes, yes, they are

Solution

That's right It's not as onerous as it sounds, because the rule of thumb is that you just need to override hashcode () if you override equals () You don't have to worry about using the default equals () class; The default hashcode () is sufficient

In addition, for your class, you only need to hash the fields you compare in the equals () method For example, if one of the fields is a unique identifier, just check the field in equals() and hash it in hashcode()

It all depends on whether you also override equals () If you don't overwrite it, don't bother hashcode()

Yes, you can rely on any collection type in the Java standard library to implement hashcode () correctly Yes, any list or set will consider its contents (it will mix the hash codes of items together)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>