So I have this linked list class:
public class LinkedList {
private LLNode rootNode;
public Node FindItemByData(String data) {
if(rootNode == null)
return null;
else
return rootNode.findItemByData(data);
}
And this node class:
public class LLNode {
LLNode tail; //tail node
Node data; //some data
public LLNode(LLNode tail, Node data)
{
this.tail = tail;
this.data = data;
}
public Node findItemByData(String data) {
if(this.data.name.equals(data))
return this.data;
else
return this.tail.findItemByData(data);
}
I want to re-use the linked list for storing edges in a graph within each Node data of the LLNode. I had a go at replacing the type using Generic Types but this breaks the functionality of the findItemByData function as it relies on data being explicitly declared as a Node.
Is there any way I can reuse this class for multiple types? Or should I not be referring to data.name in a Generic Class?
Implementation context:
public class Graph {
//USE LINKED LIST
LinkedList Nodes;
//Node[] Nodes;
int noOfNodes;
public Graph() {
noOfNodes = 0;
//Nodes = new Node[25];
Nodes = new LinkedList();
}
public void AddNode(String name, int x, int y) {
//Nodes[noOfNodes++] = new Node(name,x,y);
Nodes.AddItem(new Node(name,x,y));
}
..
public class Node {
String name; //Node's name
int x,y; //Node's coords
LinkedList Adjacencies;
int noOfAdj = 0;
int size = 0;
public Node(String name, int x, int y) { //Constructor
this.name = name;
this.x = x;
this.y = y;
Adjacencies = new LinkedList();
}
public void addAdjacency(String dest, double distance) {
Adjacencies.AddItem(new Edge(this.name, dest, distance)); //I want to do this
}
}
Edit: attempt at using generics:
public class LinkedList<T> {
private LLNode rootNode;
public T FindItemByData(String data) {
if(rootNode == null)
return null;
else
return rootNode.findItemByData(data);
}
}
public class LLNode<T> {
LLNode tail; //tail node
T data; //some data
public LLNode(LLNode tail, T data)
{
this.tail = tail;
this.data = data;
}
public T findItemByData(String data) {
if(this.data.name.equals(data))
return (T) this.data;
else
return (T) this.tail.findItemByData(data);
}
}
public class Graph {
LinkedList<Node> Nodes;
int noOfNodes;
public Graph() {
noOfNodes = 0;
Nodes = new LinkedList();
}
public void AddNode(String name, int x, int y) {
Nodes.AddItem(new Node(name,x,y));
}
}
public class Node {
String name; //Node's name
int x,y; //Node's coords
LinkedList<Edge> Adjacencies;
int noOfAdj = 0;
int size = 0;
public Node(String name, int x, int y) { //Constructor
this.name = name;
this.x = x;
this.y = y;
Adjacencies = new LinkedList();
}
public void addAdjacency(String dest, double distance) {
Adjacencies.AddItem(new Edge(this.name, dest, distance)); //I want to do this
}
}
public class LLNode<T> {..}and declaring data asT databut this did not work as LLNode's methods relied on a Node type (findItemByData)