Reputation: 515
I've been given a task to implement a graph in java. It will eventually be used to test search methods (breadth first, depth first and iterative deepening). The three classes to be made have to implement three corresponding interfaces:
public interface Node {
public Node createNode(String name, int ID, float weight);
public Node[] getNeighbours();
public Edge[] getEdges();
public void addEdge(Edge e);
public void removeEdge(Edge e);
public String getName();
public int getID();
public float getWeight();
public String toString();
public interface Edge {
public Edge createEdge(String name, int ID, float weight);
public Node getStartNode();
public void setStartNode(Node n);
public Node getEndNode();
public void setEndNode(Node n);
public String getName();
public int getID();
public float getWeight();
public String toString();
public interface Graph {
public Graph createGraph(String name, int ID, Node[] nodes, Edge[] edges, Node root);
public String getName();
public Edge[] getEdges();
public void addEdge(Edge e);
public Edge getEdge(String name, int ID);
public void removeEdge(Edge e);
public Node[] getNodes();
public void addNode(Node n);
public Node getNode(String name, int ID);
public void removeNode(Node n);
public void setRoot(Node n);
public Node getRoot();
public boolean isTree(); <= optional!
public String toString();
The main method will be in the graph class.
I'm a bit confused as to why there is create methods for each class rather than constructors.
Also can anyone advise on whether I should store edges using an adjacency matrix or an adjancency list?
Any and all help will be greatly appreciated.
Thanks
Upvotes: 1
Views: 5167
Reputation: 88378
I'm with you on questioning the wisdom of placing create methods in the interface. Methods in an interface have to be implemented as instance methods in the implementing classes, and normally methods like this, when they are used in place of constructors, are class methods, namely static factory methods, which cannot appear in interfaces.
The only reason to have a creation method in a Java interface is if one is doing cloning, which does not appear to be the case here. When you implement these interfaces the creation methods will call your constructor (which you are free to implement any way you want), but these methods are kind of silly because, as instance methods, you will need to have existing objects on which to call them.
As for your second question, the choice of adjacency matrix, adjacency list, or incidence list is totally up to you.
Upvotes: 2
Reputation: 160170
Interfaces can't define constructors. For some discussion, see this wiki page.
See the wikipedia page on adjacency list tradeoffs for a brief discussion that might lead you in the right direction.
Upvotes: 1