Data Structures, Algorithms, & Applications in Java
Chapter 17, Exercise 39

We follow the derivation hierarchy used in the text for the linked adjacency list classes and derive the class ArrayWDigraph, from the class ArrayDigraph that was developed in Exercise 35. The code is given below. Changes from the code for LinkedWDigraph are shown in red.


public class ArrayWDigraph extends ArrayDigraph
{
   // constructors
   public ArrayWDigraph(int theVertices)
      {super(theVertices);}
   
   // default is a 0 vertex graph
   public ArrayWDigraph()
      {this(0);}
   
   /** put theEdge into the digraph 
     * @throws IllegalArgumentException when
     * theEdge is invalid */
   public void putEdge(Object theEdge)
   {
      WeightedEdge edge =  (WeightedEdge) theEdge;
      int v1 = edge.vertex1;
      int v2 = edge.vertex2;
      if (v1 < 1 || v2 < 1 || v1 > n || v2 > n || v1 == v2)
         throw new IllegalArgumentException
               ("(" + v1 + "," + v2 + ") is not a permissible edge");

      int index = aList[v1].indexOf(new EdgeNode(v2));
      if (index == -1)  // new edge
      {
         // put v2 at end of aList[v1]
         aList[v1].add(aList[v1].size(),
                       new WeightedEdgeNode(v2, edge.weight));
         e++;
      }
      else
      {// update edge weight
         WeightedEdgeNode e = (WeightedEdgeNode) aList[v1].get(index);
         e.weight = edge.weight;
      }
   }
}