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