2

I am trying to learn and implement Directed Graph and facing some difficulties in executing the program.

// ADD Function
public boolean addVertex(Vertex<T> v)
{
    boolean added = false;
    if (verticies.contains(v) == false)
    {
        added = verticies.add(v);
        return true;
    }
    return added;
}

class Vertex<T>
{

    private String name;
    private T data;

    /**
     * Create a Vertex with name n and given data
     *
     * @param n - name of vertex
     * @param data - data associated with vertex
     */
     public Vertex(String n, T data)
     {
         incomingEdges = new java.util.ArrayList<Edge<T>>();
         outgoingEdges = new java.util.ArrayList<Edge<T>>();
         name = n;
         this.data = data;
     }
}

// Initialization of the Vertices & Edges
public GraphImpl()
{
    verticies = new java.util.ArrayList<Vertex<T>>();
    edges = new java.util.ArrayList<Edge<T>>();
}

Error: When program is executed, I enter string as a input when the addVertex(String) function is called and it gives an error String cannot be converted to Vertex. Error Recd From Java: java.lang.ClassCastException: java.lang.String cannot be converted to DG.Vertex

Can someone please explain me, what I am doing wrong. Thank you.

user3337714
  • 663
  • 1
  • 7
  • 25
  • Please provide a better code sample. There is nothing here that shows the offending line of code calling addVertex() – HeavyE Dec 10 '14 at 16:01
  • @HeavyE I have updated the code. So when my main function calls the addVertex(String), I get String to Vertex error. – user3337714 Dec 10 '14 at 19:23

1 Answers1

1

The problem is that you don't have a function addVertex(String).

Your function is addVertex(Vertex), so you need to create a new Vertex object and add that to the Graph. The key is that a vertex requires both a name and data.

Sample Code:

DirectedGraph<String> directedGraph = new DirectedGraph<String>();
// Create a vertex object with both a name and data
Vertex<String> sampleVertex = new Vertex<String>("name", "data"):
directedGraph.addVertex(sampleVertex);

If this still doesn't solve your problem, please post an example that includes the Edge class and the main method that is attempting to call addVertex().

HeavyE
  • 2,132
  • 1
  • 23
  • 31
  • @Jared Burrows So How Will I be doing for the String? `DirectedGraph diGraph = new DirectedGraph();` `String vertexData = ?; // What is VertexData` `Vertex sample = new Vertex(data, vertexData);` `diGraph.addVertex(sample);` – user3337714 Dec 10 '14 at 23:13
  • @user3337714 I did not post the answer, only fix the formatting. – Jared Burrows Dec 11 '14 at 02:11