net.java.trueupdate.util.builder.ImmutableListBuilder Maven / Gradle / Ivy
/*
* Copyright (C) 2013 Schlichtherle IT Services & Stimulus Software.
* All rights reserved. Use is subject to license terms.
*/
package net.java.trueupdate.util.builder;
import java.util.*;
import static java.util.Collections.*;
import javax.annotation.Nullable;
/**
* A builder for immutable lists.
*
* @param The type of the list items.
* @param The type of the parent builder, if defined.
*/
public class ImmutableListBuilder extends AbstractBuilder
{
public static ImmutableListBuilder create() {
return new ImmutableListBuilder();
}
private final List items = new LinkedList();
public final ImmutableListBuilder clear() {
items.clear();
return this;
}
public final ImmutableListBuilder add(final @Nullable I item) {
items.add(item);
return this;
}
@SuppressWarnings("ManualArrayToCollectionCopy")
public final ImmutableListBuilder add(final I... items) {
for (I item : items) this.items.add(item);
return this;
}
public final ImmutableListBuilder set(@Nullable I item) {
return clear().add(item);
}
public final ImmutableListBuilder set(I... items) {
return clear().add(items);
}
public final ImmutableListBuilder addAll(
final Collection extends I> collection) {
items.addAll(collection);
return this;
}
public final ImmutableListBuilder setAll(
Collection extends I> collection) {
return clear().addAll(collection);
}
/** Builds an immutable list with the added items. */
@SuppressWarnings("unchecked")
@Override public final List build() {
final int size = items.size();
return 0 == size
? EMPTY_LIST
: 1 == size
? singletonList(items.get(0))
: unmodifiableList(new ArrayList(items));
}
}