001/* 002 * Copyright (C) 2016 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.graph; 018 019import static com.google.common.base.Preconditions.checkArgument; 020import static com.google.common.base.Preconditions.checkNotNull; 021import static com.google.common.graph.Graphs.checkNonNegative; 022 023import com.google.errorprone.annotations.CanIgnoreReturnValue; 024import com.google.errorprone.annotations.DoNotMock; 025 026/** 027 * A builder for constructing instances of {@link MutableGraph} or {@link ImmutableGraph} with 028 * user-defined properties. 029 * 030 * <p>A {@code Graph} built by this class has the following default properties: 031 * 032 * <ul> 033 * <li>does not allow self-loops 034 * <li>orders {@link Graph#nodes()} in the order in which the elements were added (insertion 035 * order) 036 * </ul> 037 * 038 * <p>{@code Graph}s built by this class also guarantee that each collection-returning accessor 039 * returns a <b>(live) unmodifiable view</b>; see <a 040 * href="https://github.com/google/guava/wiki/GraphsExplained#accessor-behavior">the external 041 * documentation</a> for details. 042 * 043 * <p>Examples of use: 044 * 045 * {@snippet : 046 * // Building a mutable graph 047 * MutableGraph<String> graph = GraphBuilder.undirected().allowsSelfLoops(true).build(); 048 * graph.putEdge("bread", "bread"); 049 * graph.putEdge("chocolate", "peanut butter"); 050 * graph.putEdge("peanut butter", "jelly"); 051 * 052 * // Building an immutable graph 053 * ImmutableGraph<String> immutableGraph = 054 * GraphBuilder.undirected() 055 * .allowsSelfLoops(true) 056 * .<String>immutable() 057 * .putEdge("bread", "bread") 058 * .putEdge("chocolate", "peanut butter") 059 * .putEdge("peanut butter", "jelly") 060 * .build(); 061 * } 062 * 063 * @author James Sexton 064 * @author Joshua O'Madadhain 065 * @param <N> The most general node type this builder will support. This is normally {@code Object} 066 * unless it is constrained by using a method like {@link #nodeOrder}, or the builder is 067 * constructed based on an existing {@code Graph} using {@link #from(Graph)}. 068 * @since 20.0 069 */ 070@DoNotMock 071public final class GraphBuilder<N> extends AbstractGraphBuilder<N> { 072 073 /** Creates a new instance with the specified edge directionality. */ 074 private GraphBuilder(boolean directed) { 075 super(directed); 076 } 077 078 /** Returns a {@link GraphBuilder} for building directed graphs. */ 079 public static GraphBuilder<Object> directed() { 080 return new GraphBuilder<>(true); 081 } 082 083 /** Returns a {@link GraphBuilder} for building undirected graphs. */ 084 public static GraphBuilder<Object> undirected() { 085 return new GraphBuilder<>(false); 086 } 087 088 /** 089 * Returns a {@link GraphBuilder} initialized with all properties queryable from {@code graph}. 090 * 091 * <p>The "queryable" properties are those that are exposed through the {@link Graph} interface, 092 * such as {@link Graph#isDirected()}. Other properties, such as {@link #expectedNodeCount(int)}, 093 * are not set in the new builder. 094 */ 095 public static <N> GraphBuilder<N> from(Graph<N> graph) { 096 return new GraphBuilder<N>(graph.isDirected()) 097 .allowsSelfLoops(graph.allowsSelfLoops()) 098 .nodeOrder(graph.nodeOrder()) 099 .incidentEdgeOrder(graph.incidentEdgeOrder()); 100 } 101 102 /** 103 * Returns an {@link ImmutableGraph.Builder} with the properties of this {@link GraphBuilder}. 104 * 105 * <p>The returned builder can be used for populating an {@link ImmutableGraph}. 106 * 107 * <p>Note that the returned builder will always have {@link #incidentEdgeOrder} set to {@link 108 * ElementOrder#stable()}, regardless of the value that was set in this builder. 109 * 110 * @since 28.0 111 */ 112 public <N1 extends N> ImmutableGraph.Builder<N1> immutable() { 113 GraphBuilder<N1> castBuilder = cast(); 114 return new ImmutableGraph.Builder<>(castBuilder); 115 } 116 117 /** 118 * Specifies whether the graph will allow self-loops (edges that connect a node to itself). 119 * Attempting to add a self-loop to a graph that does not allow them will throw an {@link 120 * UnsupportedOperationException}. 121 * 122 * <p>The default value is {@code false}. 123 */ 124 @CanIgnoreReturnValue 125 public GraphBuilder<N> allowsSelfLoops(boolean allowsSelfLoops) { 126 this.allowsSelfLoops = allowsSelfLoops; 127 return this; 128 } 129 130 /** 131 * Specifies the expected number of nodes in the graph. 132 * 133 * @throws IllegalArgumentException if {@code expectedNodeCount} is negative 134 */ 135 @CanIgnoreReturnValue 136 public GraphBuilder<N> expectedNodeCount(int expectedNodeCount) { 137 this.expectedNodeCount = checkNonNegative(expectedNodeCount); 138 return this; 139 } 140 141 /** 142 * Specifies the order of iteration for the elements of {@link Graph#nodes()}. 143 * 144 * <p>The default value is {@link ElementOrder#insertion() insertion order}. 145 */ 146 public <N1 extends N> GraphBuilder<N1> nodeOrder(ElementOrder<N1> nodeOrder) { 147 GraphBuilder<N1> newBuilder = cast(); 148 newBuilder.nodeOrder = checkNotNull(nodeOrder); 149 return newBuilder; 150 } 151 152 /** 153 * Specifies the order of iteration for the elements of {@link Graph#edges()}, {@link 154 * Graph#adjacentNodes(Object)}, {@link Graph#predecessors(Object)}, {@link 155 * Graph#successors(Object)} and {@link Graph#incidentEdges(Object)}. 156 * 157 * <p>The default value is {@link ElementOrder#unordered() unordered} for mutable graphs. For 158 * immutable graphs, this value is ignored; they always have a {@link ElementOrder#stable() 159 * stable} order. 160 * 161 * @throws IllegalArgumentException if {@code incidentEdgeOrder} is not either {@code 162 * ElementOrder.unordered()} or {@code ElementOrder.stable()}. 163 * @since 29.0 164 */ 165 public <N1 extends N> GraphBuilder<N1> incidentEdgeOrder(ElementOrder<N1> incidentEdgeOrder) { 166 checkArgument( 167 incidentEdgeOrder.type() == ElementOrder.Type.UNORDERED 168 || incidentEdgeOrder.type() == ElementOrder.Type.STABLE, 169 "The given elementOrder (%s) is unsupported. incidentEdgeOrder() only supports" 170 + " ElementOrder.unordered() and ElementOrder.stable().", 171 incidentEdgeOrder); 172 GraphBuilder<N1> newBuilder = cast(); 173 newBuilder.incidentEdgeOrder = checkNotNull(incidentEdgeOrder); 174 return newBuilder; 175 } 176 177 /** Returns an empty {@link MutableGraph} with the properties of this {@link GraphBuilder}. */ 178 public <N1 extends N> MutableGraph<N1> build() { 179 return new StandardMutableGraph<>(this); 180 } 181 182 GraphBuilder<N> copy() { 183 GraphBuilder<N> newBuilder = new GraphBuilder<>(directed); 184 newBuilder.allowsSelfLoops = allowsSelfLoops; 185 newBuilder.nodeOrder = nodeOrder; 186 newBuilder.expectedNodeCount = expectedNodeCount; 187 newBuilder.incidentEdgeOrder = incidentEdgeOrder; 188 return newBuilder; 189 } 190 191 @SuppressWarnings("unchecked") 192 private <N1 extends N> GraphBuilder<N1> cast() { 193 return (GraphBuilder<N1>) this; 194 } 195}