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