2 package net.pterodactylus.util.data;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.Comparator;
7 import java.util.Iterator;
11 * Implementation of the {@link Node} interface.
13 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
15 * The type of the element to store
17 class NodeImpl<E extends Comparable<E>> implements Node<E> {
19 /** The parent node of this node. */
20 private final Node<E> parentNode;
22 /** The element contained in this node. */
23 private final E element;
25 /** The child nodes of this node. */
26 private final List<Node<E>> children = new ArrayList<Node<E>>();
29 * Creates a new root node.
32 this.parentNode = null;
37 * Creates a new node with the given parent and element.
40 * The parent of this node
42 * The element of this node
44 NodeImpl(Node<E> parentNode, E element) {
45 if ((parentNode == null) || (element == null)) {
46 throw new NullPointerException("null is not allowed as parent or element");
48 this.parentNode = parentNode;
49 this.element = element;
55 public Node<E> getParent() {
62 public E getElement() {
69 public Node<E> addChild(E child) {
70 Node<E> childNode = new NodeImpl<E>(this, child);
71 children.add(childNode);
79 return children.size();
85 public Node<E> getChild(int childIndex) {
86 return children.get(childIndex);
92 public Node<E> getChild(E element) {
93 for (Node<E> childNode: children) {
94 if (childNode.getElement().equals(element)) {
104 public boolean hasChild(Node<E> childNode) {
105 return children.contains(childNode);
111 public boolean hasChild(E element) {
112 for (Node<E> childNode: children) {
113 if (childNode.getElement().equals(element)) {
123 public int getIndexOfChild(Node<E> childNode) {
125 for (Node<E> node: children) {
126 if (node.equals(childNode)) {
137 public int getIndexOfChild(E element) {
139 for (Node<E> node: children) {
140 if (node.getElement().equals(element)) {
151 public void removeChild(Node<E> childNode) {
152 children.remove(childNode);
158 public void removeChild(E child) {
159 for (Node<E> childNode: children) {
160 if (child.equals(childNode.getElement())) {
161 children.remove(childNode);
170 public void removeChild(int childIndex) {
171 children.remove(childIndex);
177 public void removeAllChildren() {
184 public Iterator<Node<E>> iterator() {
185 return children.iterator();
191 public Node<E> findChild(E element) {
192 for (Node<E> childNode: children) {
193 Node<E> wantedNode = childNode.findChild(element);
194 if (wantedNode != null) {
198 if (this.element.equals(element)) {
207 public void sortChildren() {
208 Collections.sort(children);
214 public void sortChildren(Comparator<Node<E>> comparator) {
215 Collections.sort(children, comparator);
219 // INTERFACE Comparable
225 public int compareTo(Node<E> otherNode) {
226 return element.compareTo(otherNode.getElement());