1 /* 2 * Copyright (C) 2017 The Dagger Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package dagger.internal; 18 19 import static dagger.internal.Preconditions.checkNotNull; 20 21 import java.util.ArrayList; 22 import java.util.Collection; 23 import java.util.Collections; 24 import java.util.HashSet; 25 import java.util.List; 26 import java.util.Set; 27 28 /** 29 * A fluent builder class that returns a {@link Set}. Used in component implementations where a set 30 * must be created in one fluent statement for inlined request fulfillments. 31 */ 32 public final class SetBuilder<T> { 33 private static final String SET_CONTRIBUTIONS_CANNOT_BE_NULL = 34 "Set contributions cannot be null"; 35 private final List<T> contributions; 36 SetBuilder(int estimatedSize)37 private SetBuilder(int estimatedSize) { 38 contributions = new ArrayList<>(estimatedSize); 39 } 40 41 /** 42 * {@code estimatedSize} is the number of bindings which contribute to the set. They may each 43 * provide {@code [0..n)} instances to the set. Because the final size is unknown, {@code 44 * contributions} are collected in a list and only hashed in {@link #build()}. 45 */ newSetBuilder(int estimatedSize)46 public static <T> SetBuilder<T> newSetBuilder(int estimatedSize) { 47 return new SetBuilder<T>(estimatedSize); 48 } 49 add(T t)50 public SetBuilder<T> add(T t) { 51 contributions.add(checkNotNull(t, SET_CONTRIBUTIONS_CANNOT_BE_NULL)); 52 return this; 53 } 54 addAll(Collection<? extends T> collection)55 public SetBuilder<T> addAll(Collection<? extends T> collection) { 56 for (T item : collection) { 57 checkNotNull(item, SET_CONTRIBUTIONS_CANNOT_BE_NULL); 58 } 59 contributions.addAll(collection); 60 return this; 61 } 62 build()63 public Set<T> build() { 64 if (contributions.isEmpty()) { 65 return Collections.emptySet(); 66 } else if (contributions.size() == 1) { 67 return Collections.singleton(contributions.get(0)); 68 } else { 69 return Collections.unmodifiableSet(new HashSet<>(contributions)); 70 } 71 } 72 } 73