# How to achieve collision-free "hash codes" in one single Julia session?

**URL:** https://discourse.julialang.org/t/how-to-achieve-collision-free-hash-codes-in-one-single-julia-session/123428
**Category:** General Usage
**Tags:** hash
**Created:** [December 3, 2024, 10:03pm UTC](https://discourse.julialang.org/t/how-to-achieve-collision-free-hash-codes-in-one-single-julia-session/123428 "2024-12-03T22:03:13Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![frankwswang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/frankwswang/32/18561_2.png) [@frankwswang](https://discourse.julialang.org/u/frankwswang)
#### Post date: [December 3, 2024, 10:03pm UTC](https://discourse.julialang.org/t/how-to-achieve-collision-free-hash-codes-in-one-single-julia-session/123428/1 "2024-12-03T22:03:13Z")

</div>

I have many mixed composite-type instances that I need to compare their equality (by `===`) when I don’t necessarily (want to) have access to them directly.

I do not want to directly store a reference (like `Ref` or a `struct`) pointing to the original object because, I would have to manually free these references to allow garbage collection.

So far, what I have done is storing the hash values of them using `objectid` in separate containers for comparison. However, I would like to avoid possible hash collision so that I can guarantee the equality of two objects when their hash codes (or other homogenous identifiers that are not strictly hash codes) are the same.

Is there any efficient way to achieve this? Thanks very much!

---

<div class="post-metadata">

### Author: ![sgaure](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sgaure/32/14779_2.png) [@sgaure](https://discourse.julialang.org/u/sgaure)
#### Post date: [December 3, 2024, 10:42pm UTC](https://discourse.julialang.org/t/how-to-achieve-collision-free-hash-codes-in-one-single-julia-session/123428/2 "2024-12-03T22:42:08Z")

</div>

> [@frankwswang](#):
>
> I do not want to directly store a reference (like `Ref` or a `struct`) pointing to the original object because, I would have to manually free these references to allow garbage collection.

You can store a `WeakRef`, and compare them via their `.value` component. Hashes can’t be guaranteed to not collide, although it happens infrequently.

---

<div class="post-metadata">

### Author: ![frankwswang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/frankwswang/32/18561_2.png) [@frankwswang](https://discourse.julialang.org/u/frankwswang)
#### Post date: [December 3, 2024, 11:08pm UTC](https://discourse.julialang.org/t/how-to-achieve-collision-free-hash-codes-in-one-single-julia-session/123428/3 "2024-12-03T23:08:19Z")

</div>

This seems like a good middle-way solution. Thanks!
