DirectedGraph: addVertex(Vertex<T> v), String cannot be converted to Vertex

1.3k views Asked by At

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.

1

There are 1 answers

2
HeavyE On

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().