From 7becd89b1d564933e5192593d086f718aeaa8b96 Mon Sep 17 00:00:00 2001 From: themode Date: Thu, 30 Dec 2021 10:10:07 +0100 Subject: [PATCH] Test for ObjectArray --- .../minestom/server/utils/ObjectArray.java | 15 ++++++---- src/test/java/utils/ObjectArrayTest.java | 28 +++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) create mode 100644 src/test/java/utils/ObjectArrayTest.java diff --git a/src/main/java/net/minestom/server/utils/ObjectArray.java b/src/main/java/net/minestom/server/utils/ObjectArray.java index 50544ca46..0d470a3e8 100644 --- a/src/main/java/net/minestom/server/utils/ObjectArray.java +++ b/src/main/java/net/minestom/server/utils/ObjectArray.java @@ -21,23 +21,26 @@ public final class ObjectArray { } public void set(int index, T object) { + T[] array = this.array; if (index >= array.length) { - T[] newArray = allocate(index * 2 + 1); - System.arraycopy(array, 0, newArray, 0, array.length); - this.array = newArray; + T[] temp = allocate(index * 2 + 1); + System.arraycopy(array, 0, temp, 0, array.length); + this.array = array = temp; } array[index] = object; this.max = Math.max(max, index); } public T get(int index) { + final T[] array = this.array; return index < array.length ? array[index] : null; } public void trim() { - T[] newArray = allocate(max + 1); - System.arraycopy(array, 0, newArray, 0, max + 1); - this.array = newArray; + final int max = this.max; + T[] temp = allocate(max + 1); + System.arraycopy(array, 0, temp, 0, max + 1); + this.array = temp; } private static T[] allocate(int length) { diff --git a/src/test/java/utils/ObjectArrayTest.java b/src/test/java/utils/ObjectArrayTest.java new file mode 100644 index 000000000..06c6a47b6 --- /dev/null +++ b/src/test/java/utils/ObjectArrayTest.java @@ -0,0 +1,28 @@ +package utils; + +import net.minestom.server.utils.ObjectArray; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ObjectArrayTest { + + @Test + public void testArray() { + ObjectArray array = new ObjectArray<>(); + + array.set(50, "Hey"); + assertEquals("Hey", array.get(50)); + + array.set(0, "Hey2"); + assertEquals("Hey2", array.get(0)); + assertEquals("Hey", array.get(50)); + + array.trim(); + + array.set(250, "Hey3"); + assertEquals("Hey3", array.get(250)); + assertEquals("Hey2", array.get(0)); + assertEquals("Hey", array.get(50)); + } +}