Updated version from Graph Implementation in Java using adjacency list
public class MyGraph {
// add vertex name as key, and neighbors as values in set
HashMap<String, HashSet<String>> adjList = new HashMap<>();
public void addVertex(String name) {
if (adjList.containsKey(name)) {
throw new IllegalArgumentException();
}
adjList.put(name, new HashSet<>());
}
public void addEdge(String source, String destination) {
// are both vertexes already in the graph?
if (!adjList.containsKey(source) || !adjList.containsKey(destination)) {
throw new IllegalArgumentException();
}
// does edge already exist?
if (adjList.get(source).contains(destination)) {
throw new IllegalArgumentException();
} else {
adjList.get(source).add(destination);
}
}
public HashSet<String> getNeighbors(String name) {
return adjList.get(name);
}
// return true if there is an edge from source -> destination
public boolean isNeighbor(String source, String destination) {
if (!adjList.containsKey(source) || !adjList.containsKey(destination)) {
throw new IllegalArgumentException();
}
return adjList.get(source).contains(destination);
}
public void removeEdge(String source, String destination) {
if (!adjList.containsKey(source) || !adjList.containsKey(destination)) {
throw new IllegalArgumentException();
}
adjList.get(source).remove(destination);
}
public void removeVertex(String name) {
if (!adjList.containsKey(name)) {
throw new IllegalArgumentException();
}
// remove vertex and its neighbors, if any
adjList.remove(name);
// remove vertex as a neighbors from other vertexes
Set vertexes = adjList.keySet();
Iterator i = vertexes.iterator();
while (i.hasNext()) {
String vertex = (String) i.next();
if (adjList.get(vertex).contains(name)) {
adjList.get(vertex).remove(name);
}
}
}
// removes all vertexes/edges from graph
public void clear() {
adjList = new HashMap<>();
}
// returns the number of vertexes
public int size() {
return adjList.size();
}
public boolean isEmpty() {
return adjList.isEmpty();
}
}