View Javadoc
1   /*
2    * Created on Oct 18, 2005
3    *
4    * Copyright (c) 2005, The JUNG Authors 
5    *
6    * All rights reserved.
7    *
8    * This software is open-source under the BSD license; see either
9    * "license.txt" or
10   * https://github.com/jrtom/jung/blob/master/LICENSE for a description.
11   */
12  package edu.uci.ics.jung.graph;
13  
14  import java.util.Collection;
15  import java.util.Collections;
16  import java.util.LinkedHashMap;
17  import java.util.LinkedHashSet;
18  import java.util.Set;
19  
20  import com.google.common.base.Supplier;
21  
22  import edu.uci.ics.jung.graph.util.Pair;
23  
24  /**
25   * An implementation of <code>UndirectedGraph</code> that is suitable for sparse graphs,
26   * orders its vertex and edge collections according to insertion time, and permits
27   * parallel edges.
28   */
29  @SuppressWarnings("serial")
30  public class UndirectedOrderedSparseMultigraph<V,E> 
31      extends UndirectedSparseMultigraph<V,E>
32      implements UndirectedGraph<V,E> {
33  	
34      /**
35       * @param <V> the vertex type for the graph Supplier
36       * @param <E> the edge type for the graph Supplier
37       * @return a {@code Supplier} that creates an instance of this graph type.
38       */
39  	public static <V,E> Supplier<UndirectedGraph<V,E>> getFactory() {
40  		return new Supplier<UndirectedGraph<V,E>> () {
41  			public UndirectedGraph<V,E> get() {
42  				return new UndirectedOrderedSparseMultigraph<V,E>();
43  			}
44  		};
45  	}
46  
47  	/**
48  	 * Creates a new instance.
49  	 */
50      public UndirectedOrderedSparseMultigraph() {
51          vertices = new LinkedHashMap<V, Set<E>>();
52          edges = new LinkedHashMap<E, Pair<V>>();
53      }
54  
55      @Override
56      public boolean addVertex(V vertex) {
57      	if(vertex == null) {
58      		throw new IllegalArgumentException("vertex may not be null");
59      	}
60          if (!containsVertex(vertex))
61          {
62              vertices.put(vertex, new LinkedHashSet<E>());
63              return true;
64          } else {
65              return false;
66          }
67      }
68  
69      @Override
70      public Collection<V> getNeighbors(V vertex) {
71          if (!containsVertex(vertex))
72              return null;
73          
74          Set<V> neighbors = new LinkedHashSet<V>();
75          for (E edge : getIncident_internal(vertex))
76          {
77              Pair<V> endpoints = this.getEndpoints(edge);
78              V e_a = endpoints.getFirst();
79              V e_b = endpoints.getSecond();
80              if (vertex.equals(e_a))
81                  neighbors.add(e_b);
82              else
83                  neighbors.add(e_a);
84          }
85          
86          return Collections.unmodifiableCollection(neighbors);
87      }
88  }