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