Skip to content

Instantly share code, notes, and snippets.

@PegasisForever
Last active January 14, 2020 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PegasisForever/1646c73f458a44df20bf68999a370ea4 to your computer and use it in GitHub Desktop.
Save PegasisForever/1646c73f458a44df20bf68999a370ea4 to your computer and use it in GitHub Desktop.
An example of graph in java
import java.util.ArrayList;
//Definition of Node
class Node {
String name; // Name of the node
ArrayList<Node> connectedNodes = new ArrayList<>(); // All nodes connected to this node
// Constructor, called when use `new Node("name")`
Node(String n) {
name = n;
}
// Tell system how to convert a Node object to a String (used in println)
public String toString() {
return "Node " + name;
}
// Connect two nodes
// `static` means you can use this method without `**new** Node()`
static void connect(Node n1, Node n2){
n1.connectedNodes.add(n2); // Add node2 to the list of connected nodes in node1
n2.connectedNodes.add(n1); // Add node1 to the list of connected nodes in node2
}
}
public class Main {
// The following code creates a graph like ↓ and print all connected nodes of node A
// A------B
// | |
// C------D
public static void main(String[] args) {
Node nodeA = new Node("A");
Node nodeB = new Node("B");
Node nodeC = new Node("C");
Node nodeD = new Node("D");
Node.connect(nodeA, nodeB);
Node.connect(nodeB, nodeD);
Node.connect(nodeD, nodeC);
Node.connect(nodeC, nodeA);
// Following code won't work:
// When you use `new Node("A")`, you create a new node
// `new Node("A")` and `new Node("A")` create two nodes have the same name, not one node.
// Node.connect(new Node("A"), new Node("B"));
// Node.connect(new Node("B"), new Node("D"));
// Node.connect(new Node("D"), new Node("C"));
// Node.connect(new Node("C"), new Node("A"));
printConnectedNodes(nodeA);
}
static void printConnectedNodes(Node node) {
for (Node connectedNode : node.connectedNodes) { //An alternative way to iterate through list/array
System.out.println(connectedNode);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment