From 90baa790c37c226bf2724b07cc3cbc2e0077637f Mon Sep 17 00:00:00 2001 From: Hannes Greule Date: Mon, 6 Mar 2023 13:57:40 +0100 Subject: [PATCH] Make custom toArray methods fulfill the method contract (#2089) * Make PropertyKeySet#toArray(T) fulfill the method contract * Make LocalBlockVectorSet#toArray(T) fulfill the method contract --- .../core/math/LocalBlockVectorSet.java | 8 ++++++-- .../core/registry/state/PropertyKeySet.java | 11 ++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/worldedit-core/src/main/java/com/fastasyncworldedit/core/math/LocalBlockVectorSet.java b/worldedit-core/src/main/java/com/fastasyncworldedit/core/math/LocalBlockVectorSet.java index f94bb8546..8e6cdabe8 100644 --- a/worldedit-core/src/main/java/com/fastasyncworldedit/core/math/LocalBlockVectorSet.java +++ b/worldedit-core/src/main/java/com/fastasyncworldedit/core/math/LocalBlockVectorSet.java @@ -6,6 +6,7 @@ import com.sk89q.worldedit.math.BlockVector3; import com.zaxxer.sparsebits.SparseBitSet; import javax.annotation.Nonnull; +import java.util.Arrays; import java.util.Collection; import java.util.Iterator; @@ -235,12 +236,15 @@ public class LocalBlockVectorSet implements BlockVector3Set { return toArray((Object[]) null); } + @SuppressWarnings("unchecked") @Nonnull @Override public T[] toArray(T[] array) { int size = size(); - if (array == null || array.length < size) { - array = (T[]) new BlockVector3[size]; + if (array.length < size) { + array = Arrays.copyOf(array, size); + } else if (array.length > size) { + array[size] = null; // mark as end to comply with the method contract } int index = 0; for (int i = 0; i < size; i++) { diff --git a/worldedit-core/src/main/java/com/fastasyncworldedit/core/registry/state/PropertyKeySet.java b/worldedit-core/src/main/java/com/fastasyncworldedit/core/registry/state/PropertyKeySet.java index 2a1d4258d..45cb5e89c 100644 --- a/worldedit-core/src/main/java/com/fastasyncworldedit/core/registry/state/PropertyKeySet.java +++ b/worldedit-core/src/main/java/com/fastasyncworldedit/core/registry/state/PropertyKeySet.java @@ -73,7 +73,16 @@ public class PropertyKeySet implements Set { @Nonnull @Override public T[] toArray(@Nonnull T[] a) { - T[] array = Arrays.copyOf(a, this.bits.cardinality()); + T[] array; + final int cardinality = this.bits.cardinality(); + if (cardinality > a.length) { + array = Arrays.copyOf(a, cardinality); + } else { + array = a; + if (a.length > cardinality) { + array[cardinality] = null; // mark as end to comply with the method contract + } + } Iterator iter = iterator(); for (int i = 0; i < array.length && iter.hasNext(); i++) { array[i] = (T) iter.next();