View Javadoc
1   /*
2    * Copyright (C) 2016 The Guava 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 com.google.common.graph;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  import static com.google.common.graph.Graphs.checkNonNegative;
21  
22  import com.google.common.annotations.Beta;
23  import com.google.common.base.Optional;
24  
25  /**
26   * A builder for constructing instances of {@link MutableGraph} with user-defined properties.
27   *
28   * <p>A graph built by this class will have the following properties by default:
29   *
30   * <ul>
31   * <li>does not allow self-loops
32   * <li>orders {@link Graph#nodes()} in the order in which the elements were added
33   * </ul>
34   *
35   * <p>Example of use:
36   *
37   * <pre>{@code
38   * MutableGraph<String> graph = GraphBuilder.undirected().allowsSelfLoops(true).build();
39   * graph.putEdge("bread", "bread");
40   * graph.putEdge("chocolate", "peanut butter");
41   * graph.putEdge("peanut butter", "jelly");
42   * }</pre>
43   *
44   * @author James Sexton
45   * @author Joshua O'Madadhain
46   * @since 20.0
47   */
48  @Beta
49  public final class GraphBuilder<N> extends AbstractGraphBuilder<N> {
50  
51    /** Creates a new instance with the specified edge directionality. */
52    private GraphBuilder(boolean directed) {
53      super(directed);
54    }
55  
56    /** Returns a {@link GraphBuilder} for building directed graphs. */
57    public static GraphBuilder<Object> directed() {
58      return new GraphBuilder<>(true);
59    }
60  
61    /** Returns a {@link GraphBuilder} for building undirected graphs. */
62    public static GraphBuilder<Object> undirected() {
63      return new GraphBuilder<>(false);
64    }
65  
66    /**
67     * Returns a {@link GraphBuilder} initialized with all properties queryable from {@code graph}.
68     *
69     * <p>The "queryable" properties are those that are exposed through the {@link Graph} interface,
70     * such as {@link Graph#isDirected()}. Other properties, such as {@link #expectedNodeCount(int)},
71     * are not set in the new builder.
72     */
73    public static <N> GraphBuilder<N> from(Graph<N> graph) {
74      return new GraphBuilder<N>(graph.isDirected())
75          .allowsSelfLoops(graph.allowsSelfLoops())
76          .nodeOrder(graph.nodeOrder());
77    }
78  
79    /**
80     * Specifies whether the graph will allow self-loops (edges that connect a node to itself).
81     * Attempting to add a self-loop to a graph that does not allow them will throw an {@link
82     * UnsupportedOperationException}.
83     */
84    public GraphBuilder<N> allowsSelfLoops(boolean allowsSelfLoops) {
85      this.allowsSelfLoops = allowsSelfLoops;
86      return this;
87    }
88  
89    /**
90     * Specifies the expected number of nodes in the graph.
91     *
92     * @throws IllegalArgumentException if {@code expectedNodeCount} is negative
93     */
94    public GraphBuilder<N> expectedNodeCount(int expectedNodeCount) {
95      this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
96      return this;
97    }
98  
99    /** Specifies the order of iteration for the elements of {@link Graph#nodes()}. */
100   public <N1 extends N> GraphBuilder<N1> nodeOrder(ElementOrder<N1> nodeOrder) {
101     GraphBuilder<N1> newBuilder = cast();
102     newBuilder.nodeOrder = checkNotNull(nodeOrder);
103     return newBuilder;
104   }
105 
106   /** Returns an empty {@link MutableGraph} with the properties of this {@link GraphBuilder}. */
107   public <N1 extends N> MutableGraph<N1> build() {
108     return new ConfigurableMutableGraph<N1>(this);
109   }
110 
111   @SuppressWarnings("unchecked")
112   private <N1 extends N> GraphBuilder<N1> cast() {
113     return (GraphBuilder<N1>) this;
114   }
115 }