1 package org.apache.commons.graph.model;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import static java.lang.String.format;
23
24 import java.util.HashSet;
25
26 import org.apache.commons.graph.Edge;
27 import org.apache.commons.graph.Graph;
28 import org.apache.commons.graph.GraphException;
29 import org.apache.commons.graph.MutableGraph;
30 import org.apache.commons.graph.Vertex;
31
32
33
34
35
36
37
38 public abstract class BaseMutableGraph<V extends Vertex, E extends Edge<V>>
39 extends BaseGraph<V, E>
40 implements MutableGraph<V, E>
41 {
42
43
44
45
46 public final void addVertex( V v )
47 {
48 if ( v == null )
49 {
50 throw new GraphException( "Impossible to add a null Vertex to the Graph" );
51 }
52
53 if ( getAdjacencyList().containsKey( v ) ){
54 throw new GraphException( format( "Vertex '%s' already present in the Graph", v ) );
55 }
56
57 getAdjacencyList().put( v, new HashSet<E>() );
58
59 decorateAddVertex( v );
60 }
61
62
63
64
65
66
67 protected abstract void decorateAddVertex( V v );
68
69
70
71
72 public final void removeVertex( V v )
73 {
74 if ( v == null )
75 {
76 throw new GraphException( "Impossible to remove a null Vertex from the Graph" );
77 }
78
79 if ( !getAdjacencyList().containsKey( v ) ){
80 throw new GraphException( format( "Vertex '%s' not present in the Graph", v ) );
81 }
82
83 getAdjacencyList().remove( v );
84
85 decorateRemoveVertex( v );
86 }
87
88
89
90
91
92
93 protected abstract void decorateRemoveVertex( V v );
94
95
96
97
98 public final void addEdge( E e )
99 {
100 checkEdge( e );
101
102 getAllEdges().add( e );
103 getAdjacencyList().get( e.getHead() ).add( e );
104
105 decorateAddEdge( e );
106 }
107
108
109
110
111
112
113 protected abstract void decorateAddEdge( E e );
114
115
116
117
118 public final void removeEdge( E e )
119 {
120 checkEdge( e );
121
122 getAllEdges().remove( e );
123 getAdjacencyList().get( e.getHead() ).remove( e );
124
125 decorateRemoveEdge( e );
126 }
127
128
129
130
131
132
133 protected abstract void decorateRemoveEdge( E e );
134
135
136
137
138
139
140 private final void checkEdge( E e )
141 {
142 if ( !getAdjacencyList().containsKey( e.getHead() ) )
143 {
144 throw new GraphException( format( "Vertex '%s' not present in the Graph", e.getHead() ) );
145 }
146 if ( !getAdjacencyList().containsKey( e.getTail() ) )
147 {
148 throw new GraphException( format( "Vertex '%s' not present in the Graph", e.getTail() ) );
149 }
150 }
151
152 }