LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

Why does a graph implementation validate every vertex and edge handed to it, and how does it recognise one that was already removed?

The application holds vertices and edges only through the public Vertex and Edge types, so every method first checks what it was given: that the object is one of this graph's own, and that it has not been removed. Removing an element marks it as defunct by setting its back reference to null, so a later call with the stale reference fails with an IllegalArgumentException instead of corrupting the structure.

protected VertexImpl<V> validate(Vertex<V> v) {
  if (!(v instanceof VertexImpl))
    throw new IllegalArgumentException("Invalid vertex");
  VertexImpl<V> vi = (VertexImpl<V>) v;        // back to the internal type
  if (!vi.validate(this))                      // other graph, or removed
    throw new IllegalArgumentException("Invalid vertex");
  return vi;
}

// inside the inner class VertexImpl:
boolean validate(Graph<V> graph) {
  return AdjacencyListGraph.this == graph && backReference != null;
}

Three things can be wrong with a reference the application passes in, and validate catches each:

  1. Wrong type. The public interfaces offer little more than getElement(); the graph works with its internal classes, which hold the incidence lists and back references, so it casts back to them. Checking the type first turns a foreign object into an IllegalArgumentException rather than a ClassCastException.
  2. Wrong graph. An application with two graphs could pass a vertex of the first to insertEdge of the second. The compiler cannot tell the two apart, since both vertices have the same class, so each element checks that its enclosing graph is the one asking.
  3. Removed element. After removeEdge(e) the application may still hold e and call opposite(v, e) later. The edge is unlinked from every sequence but still exists, because the application's reference keeps the garbage collector from freeing it. Removal therefore sets its back reference to null, and validate rejects any element without one.

The problem is the same as with the entries of an adaptable priority queue: once a structure hands out references to its internals, it has to check them when they come back. A boolean isAlive flag would work too; clearing the back reference needs no extra field and leaves the stale object pointing into nothing. "Defunct" is also the word Unix ps uses for a process that has ended but whose entry has not yet been collected.

From Quiz: ADS / Graphs: Basics, Representations and Spanning Trees | Updated: Nov 27, 2026