From f477f44a686d64fd93445025925f9e6be0df5259 Mon Sep 17 00:00:00 2001 From: bryanhuhta Date: Mon, 16 Dec 2024 14:46:53 -0700 Subject: [PATCH] Update equals() method to account for the type of T Also reflects the equals() change to hashCode() and adds tests for both implementations. --- .../main/java/io/pyroscope/labels/Ref.java | 10 ++++-- .../java/io/pyroscope/labels/RefTest.java | 33 +++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 async-profiler-context/src/test/java/io/pyroscope/labels/RefTest.java diff --git a/async-profiler-context/src/main/java/io/pyroscope/labels/Ref.java b/async-profiler-context/src/main/java/io/pyroscope/labels/Ref.java index 4dc0777..0ff901f 100644 --- a/async-profiler-context/src/main/java/io/pyroscope/labels/Ref.java +++ b/async-profiler-context/src/main/java/io/pyroscope/labels/Ref.java @@ -1,5 +1,6 @@ package io.pyroscope.labels; +import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; class Ref { @@ -16,13 +17,16 @@ public Ref(T val, Long id) { public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - Ref valueRef = (Ref) o; - return id.equals(valueRef.id); + + Ref valueRef = (Ref) o; + if (val.getClass() != o.getClass()) return false; + + return id.equals(valueRef.id) && val.equals(valueRef.val); } @Override public int hashCode() { - return id.hashCode(); + return Objects.hash(id, val); } @Override diff --git a/async-profiler-context/src/test/java/io/pyroscope/labels/RefTest.java b/async-profiler-context/src/test/java/io/pyroscope/labels/RefTest.java new file mode 100644 index 0000000..bde8747 --- /dev/null +++ b/async-profiler-context/src/test/java/io/pyroscope/labels/RefTest.java @@ -0,0 +1,33 @@ +package io.pyroscope.labels; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class RefTest { + @Test + void testCreateRef() { + Ref ref = new Ref<>("test", 1L); + assertEquals("test", ref.val); + assertEquals(1L, ref.id); + assertEquals(1L, ref.refCount.get()); + } + + @Test + @SuppressWarnings("unlikely-arg-type") + void testEquals() { + Ref ref1 = new Ref<>("test", 1L); + assertTrue(ref1.equals(ref1)); + assertFalse(ref1.equals(null)); + assertFalse(ref1.equals(new Integer(3))); + assertFalse(ref1.equals(new Ref(3, 1L))); + } + + @Test + void testHashCode() { + Ref ref1 = new Ref<>("test", 1L); + assertEquals(3557490, ref1.hashCode()); + } +}