I have a custom LinkedTree with children (nodes), and nodes has an adjacency relationship, i.e. each node linked with previous and next one. This LinkedTree is very heavy, big, it may consist of millions of nodes.
And here is a code sample:
package tree;
import java.io.Serializable;
public class LinkedTree<E> implements Serializable {
private int size = 0;
private Node<E> first;
private Node<E> last;
private LinkedTree<E> children;
public LinkedTree() {
children = new LinkedTree<>();
}
public LinkedTree(LinkedTree<E> children) {
this.children = children;
}
public void add(E element) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, element, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
}
public void remove(E element) {
...
}
public int size() {
return size;
}
public static class Node<E> implements Serializable {
E item;
Node<E> next;
Node<E> prev;
public Node(Node<E> prev, E item, Node<E> next) {
this.item = item;
this.next = next;
this.prev = prev;
}
public E item() {
return item;
}
public boolean hasPrevious() {
return prev != null;
}
public Node<E> previous() {
return prev;
}
public Node<E> previous(int target) {
Node<E> n = this;
int i = target;
while (i-- > 0 && n != null)
n = n.prev;
return n;
}
public boolean hasNext() {
return next != null;
}
public Node<E> next() {
return next;
}
public E nextItem() {
return next.item;
}
public E nextItem(int target) {
return next(target).item();
}
public Node<E> next(int target) {
Node<E> n = this;
int i = 0;
while (i++ < target && n != null)
n = n.next;
return n;
}
@Override
public int hashCode() {
return item != null ? item.hashCode() : 0;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Node<?> node = (Node<?>) o;
return item != null ? item.equals(node.item) : node.item == null;
}
@Override
public String toString() {
return item.toString();
}
}
}
I wanted to serialize it and save it in file in order to make it persistent, but loading and writing some data may cost too expensive. So I decided to save it in MySQL, so that I could load datas from anywhere I want. I mean from the end, middle or beginning of this hierarchy.
I suppose the relationship of the row should be in adjacency and parent-child relationship simultaneously. But I have no idea how to do it.