1 package org.apache.commons.graph.model;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import static java.util.Collections.unmodifiableSet;
23
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Map;
27 import java.util.Set;
28
29 import org.apache.commons.graph.Edge;
30 import org.apache.commons.graph.Graph;
31 import org.apache.commons.graph.Vertex;
32
33 /**
34 * Basic abstract in-memory based of a simple read-only {@link Graph} implementation.
35 *
36 * Subclasses may load adjacency list/edges set in the constructor,
37 * or expose {@link org.apache.commons.graph.MutableGraph} APIs.
38 *
39 * @param <V> the Graph vertices type
40 * @param <E> the Graph edges type
41 */
42 public abstract class BaseGraph<V extends Vertex, E extends Edge<V>>
43 implements Graph<V, E>
44 {
45
46 private final Map<V, Set<E>> adjacencyList = new HashMap<V, Set<E>>();
47
48 private final Set<E> allEdges = new HashSet<E>();
49
50 /**
51 * {@inheritDoc}
52 */
53 public final Set<V> getVertices()
54 {
55 return unmodifiableSet( adjacencyList.keySet() );
56 }
57
58 /**
59 * {@inheritDoc}
60 */
61 public final Set<E> getEdges()
62 {
63 return unmodifiableSet( allEdges );
64 }
65
66 /**
67 * {@inheritDoc}
68 */
69 public final Set<E> getEdges( V v )
70 {
71 return unmodifiableSet( adjacencyList.get( v ) );
72 }
73
74 /**
75 * {@inheritDoc}
76 */
77 public final Set<V> getVertices( E e )
78 {
79 Set<V> vertices = new HashSet<V>();
80
81 vertices.add( e.getHead() );
82 vertices.add( e.getTail() );
83
84 return unmodifiableSet( vertices );
85 }
86
87 /**
88 * Returns the adjacency list where stored vertex/edges.
89 *
90 * @return the adjacency list where stored vertex/edges.
91 */
92 protected final Map<V, Set<E>> getAdjacencyList()
93 {
94 return adjacencyList;
95 }
96
97 /**
98 * Returns the set with all Graph edges.
99 *
100 * @return the set with all Graph edges.
101 */
102 protected final Set<E> getAllEdges()
103 {
104 return allEdges;
105 }
106
107 }