Sambhav Khandelwal
Sambhav Khandelwal

Reputation: 3765

What is the use of hashcode in Document Snapshot?

I noticed this code in the DocumentSnapshot class of firebase:

@Override
public int hashCode() {
    int hash = firestore.hashCode();
    hash = hash * 31 + key.hashCode();
    hash = hash * 31 + (doc != null ? doc.getKey().hashCode() : 0);
    hash = hash * 31 + (doc != null ? doc.getData().hashCode() : 0);
    hash = hash * 31 + metadata.hashCode();
    return hash;
}

Now, even if I fetch the same document, I get a different hashcode. If they are different, what's the use of this? I get it for a class like String. It gives the same hashcode when giving it the same string. Then why different for DocumentSnapshot?

Upvotes: 0

Views: 312

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317760

This method isn't intended to be used as a way of identifying if two document snapshots are the same. It's not really part of the API surface that developers use directly. You should probably just ignore it completely unless you have a specific problem with it.

hashCode here has the same purpose that any subclass of Object would use for hashCode. From the API docs:

This method is supported for the benefit of hash tables such as those provided by HashMap.

This implementation lets the DocumentSnapshot object work well with HashMap or other collections that require a hashCode implementation. You can trust that it works fine. If you think there is a bug or problem here that you can duplicate, then file a bug on GitHub with your observations.

Upvotes: 1

Related Questions