Test for ObjectArray

This commit is contained in:
themode 2021-12-30 10:10:07 +01:00 committed by TheMode
parent e87b3bf9c3
commit 7becd89b1d
2 changed files with 37 additions and 6 deletions

View File

@ -21,23 +21,26 @@ public final class ObjectArray<T> {
}
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> T[] allocate(int length) {

View File

@ -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<String> 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));
}
}