Skip to content

Instantly share code, notes, and snippets.

Created January 4, 2017 12:06
What would you like to do?
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Graph<T> {
private HashMap<T, Set<T>> adjacencyList;
public Graph() {
this.adjacencyList = new HashMap<>();
public void addVertex(T v) {
if (this.adjacencyList.containsKey(v)) {
throw new IllegalArgumentException("Vertex exists.");
this.adjacencyList.put(v, new HashSet<T>());
public void addEdge(T v, T u) {
if (!(this.adjacencyList.containsKey(v) && this.adjacencyList.containsKey(u))) {
throw new IllegalArgumentException();
} else {
public Iterable<T> getNeighbors(T v) {
return this.adjacencyList.get(v);
public Iterable<T> getAllVertices() {
return this.adjacencyList.keySet();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment