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 { | |
this.adjacencyList.get(v).add(u); | |
this.adjacencyList.get(u).add(v); | |
} | |
} | |
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