dev.marksman.collectionviews.RepeatingVector 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 com.jnape.palatable.lambda.functions.Fn1;
import dev.marksman.enhancediterables.ImmutableFiniteIterable;
import java.util.Objects;
import static com.jnape.palatable.lambda.adt.Maybe.just;
import static com.jnape.palatable.lambda.adt.Maybe.nothing;
import static dev.marksman.collectionviews.Validation.*;
final class RepeatingVector extends ConcreteVector
implements ImmutableNonEmptyVector, Primitive {
private final int size; // must be >= 1
private final A value;
RepeatingVector(int size, A value) {
assert (size >= 1);
this.size = size;
this.value = value;
}
@Override
public A head() {
return value;
}
@Override
public ImmutableFiniteIterable filter(Fn1 super A, ? extends Boolean> predicate) {
return takeWhile(predicate);
}
@Override
public A last() {
return value;
}
@Override
public int size() {
return size;
}
@Override
public A unsafeGet(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return value;
}
@Override
public Maybe find(Fn1 super A, ? extends Boolean> predicate) {
Objects.requireNonNull(predicate);
if (predicate.apply(value)) {
return just(value);
} else {
return nothing();
}
}
@Override
public Maybe findIndex(Fn1 super A, ? extends Boolean> predicate) {
Objects.requireNonNull(predicate);
if (predicate.apply(value)) {
return just(0);
} else {
return nothing();
}
}
@Override
public ImmutableNonEmptyVector fmap(Fn1 super A, ? extends B> f) {
Objects.requireNonNull(f);
return new RepeatingVector<>(size, f.apply(value));
}
@Override
public int hashCode() {
final int h = value == null ? 0 : value.hashCode();
int hashCode = 1;
for (int i = 0; i < size; i++) {
hashCode = 31 * hashCode + h;
}
return hashCode;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (o instanceof RepeatingVector>) {
RepeatingVector