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
This commit is contained in:
Hannes Greule 2023-03-06 13:57:40 +01:00 committed by GitHub
parent a63037b92d
commit 90baa790c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 3 deletions

View File

@ -6,6 +6,7 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.zaxxer.sparsebits.SparseBitSet; import com.zaxxer.sparsebits.SparseBitSet;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
@ -235,12 +236,15 @@ public class LocalBlockVectorSet implements BlockVector3Set {
return toArray((Object[]) null); return toArray((Object[]) null);
} }
@SuppressWarnings("unchecked")
@Nonnull @Nonnull
@Override @Override
public <T> T[] toArray(T[] array) { public <T> T[] toArray(T[] array) {
int size = size(); int size = size();
if (array == null || array.length < size) { if (array.length < size) {
array = (T[]) new BlockVector3[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; int index = 0;
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {

View File

@ -73,7 +73,16 @@ public class PropertyKeySet implements Set<PropertyKey> {
@Nonnull @Nonnull
@Override @Override
public <T> T[] toArray(@Nonnull T[] a) { public <T> 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<PropertyKey> iter = iterator(); Iterator<PropertyKey> iter = iterator();
for (int i = 0; i < array.length && iter.hasNext(); i++) { for (int i = 0; i < array.length && iter.hasNext(); i++) {
array[i] = (T) iter.next(); array[i] = (T) iter.next();