dev.marksman.collectionviews.EmptyVectorBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of collection-views Show documentation
Show all versions of collection-views Show documentation
Low overhead, protected views over Java collections
package dev.marksman.collectionviews;
import com.jnape.palatable.lambda.adt.Maybe;
import dev.marksman.enhancediterables.FiniteIterable;
import dev.marksman.enhancediterables.NonEmptyFiniteIterable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import static dev.marksman.collectionviews.ConcreteVectorBuilder.concreteVectorBuilder;
final class EmptyVectorBuilder implements VectorBuilder {
private final Maybe initialCapacity;
private EmptyVectorBuilder(Maybe initialCapacity) {
this.initialCapacity = initialCapacity;
}
@Override
public NonEmptyVectorBuilder add(A element) {
ArrayList underlying = createNewUnderlying();
underlying.add(element);
return concreteVectorBuilder(underlying.size(), initialCapacity, underlying);
}
@Override
public VectorBuilder addAll(Collection elements) {
Objects.requireNonNull(elements);
if (elements.isEmpty()) {
return this;
} else {
ArrayList underlying = createNewUnderlying();
underlying.addAll(elements);
return concreteVectorBuilder(underlying.size(), initialCapacity, underlying);
}
}
@Override
public VectorBuilder addAll(FiniteIterable elements) {
Objects.requireNonNull(elements);
if (elements.isEmpty()) {
return this;
} else {
return addAllImpl(elements);
}
}
@Override
public NonEmptyVectorBuilder addAll(NonEmptyFiniteIterable elements) {
return addAllImpl(elements);
}
@Override
public ImmutableVector build() {
return Vector.empty();
}
private NonEmptyVectorBuilder addAllImpl(FiniteIterable elements) {
ArrayList underlying = createNewUnderlying();
for (A element : elements) {
underlying.add(element);
}
return concreteVectorBuilder(underlying.size(), initialCapacity, underlying);
}
private ArrayList createNewUnderlying() {
return initialCapacity.match(__ -> new ArrayList<>(), ArrayList::new);
}
static EmptyVectorBuilder emptyVectorBuilder(Maybe initialCapacity) {
return new EmptyVectorBuilder<>(initialCapacity.filter(n -> n >= 0));
}
}