t-digest icon indicating copy to clipboard operation
t-digest copied to clipboard

TDigest with custom equals and hashcode implementation

Open nagarajatantry opened this issue 3 years ago • 2 comments

I have a use case to compare if 2 tdigest's are equal. Was wondering if it makes sense to override the equals and hashcode functions in MergingDigest class.

Sample code

 @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof MergingDigest)) {
            return false;
        }
        MergingDigest compare = (MergingDigest) o;

        if (compare.size() != this.size()){
            return false;
        }
        byte[] bBytes = new byte[compare.byteSize()];
        compare.asBytes(ByteBuffer.wrap(bBytes));

        byte[] aBytes = new byte[this.byteSize()];
        this.asBytes(ByteBuffer.wrap(aBytes));
        return Arrays.equals(aBytes,bBytes);
    }

    @Override
    public int hashCode() {
        byte[] aBytes = new byte[this.byteSize()];
        this.asBytes(ByteBuffer.wrap(aBytes));
        String sketch = Base64.getEncoder().encodeToString(aBytes);
        return new HashCodeBuilder(17, 37)
                .append(sketch)
                .toHashCode();
    }

nagarajatantry avatar Jul 01 '21 14:07 nagarajatantry

This makes sense and could even be implemented at the level of the TDigest class itself (with the addition of a comparison on class).

I don't think that it will be terribly useful, but it is a plausible definition.

Do you want to create a pull request?

On Thu, Jul 1, 2021 at 7:48 AM Naga @.***> wrote:

I have a use case to compare if 2 tdigest's are equal. Was wondering if it makes sense to override the equals and hashcode functions in MergingDigest class.

Sample code

@Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof MergingDigest)) { return false; } MergingDigest compare = (MergingDigest) o;

    if (compare.size() != this.size()){
        return false;
    }
    byte[] bBytes = new byte[compare.byteSize()];
    compare.asBytes(ByteBuffer.wrap(bBytes));

    byte[] aBytes = new byte[this.byteSize()];
    this.asBytes(ByteBuffer.wrap(aBytes));
    return Arrays.equals(aBytes,bBytes);
}

@Override
public int hashCode() {
    byte[] aBytes = new byte[this.byteSize()];
    this.asBytes(ByteBuffer.wrap(aBytes));
    String sketch = Base64.getEncoder().encodeToString(aBytes);
    return new HashCodeBuilder(17, 37)
            .append(sketch)
            .toHashCode();
}

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/tdunning/t-digest/issues/176, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAB5E6XPFX4PVRX4SSFIVPLTVR55HANCNFSM47U4FJKA .

tdunning avatar Jul 01 '21 16:07 tdunning

Thank you. I will send a PR

nagarajatantry avatar Jul 01 '21 17:07 nagarajatantry