All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.java.trueupdate.util.builder.ImmutableListBuilder Maven / Gradle / Ivy

There is a newer version: 0.8.1
Show newest version
/*
 * 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 collection) { items.addAll(collection); return this; } public final ImmutableListBuilder setAll( Collection 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)); } }