LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

How do you implement opposite(v, e), and what is it used for?

Fetch the two end vertices of e with endVertices(e) and return the one that is not v; if v is neither end, the call is an error and throws an IllegalArgumentException. It runs in $O(1)$, and it is how code walks from a vertex across one of its edges to the neighbour on the other side.

public Vertex<V> opposite(Vertex<V> v, Edge<E> e) {
  Vertex<V>[] ends = endVertices(e);
  if (v == ends[0]) return ends[1];
  if (v == ends[1]) return ends[0];
  throw new IllegalArgumentException("edge is not incident on vertex");
}

The comparison uses ==, identity, on purpose: vertices are position objects, and two different vertices may well store equal elements.

The typical use is the loop that visits all neighbours of a vertex, which every graph traversal is built on:

for (Edge<E> e : incidentEdges(v)) {
  Vertex<V> w = opposite(v, e);   // the neighbour across e
  // ... work with w
}

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