/simulatest-environment/src/main/java/org/simulatest/environment/tree/Node.java

http://github.com/gabrielsuch/simulatest · Java · 79 lines · 58 code · 21 blank · 0 comment · 5 complexity · 134789df0af667428583d35036c8bb2a MD5 · raw file

  1. package org.simulatest.environment.tree;
  2. import java.util.LinkedList;
  3. public class Node<T> {
  4. private T value;
  5. private Node<T> parent;
  6. private LinkedList<Node<T>> children;
  7. public Node(T value) {
  8. this.value = value;
  9. this.children = new LinkedList<Node<T>>();
  10. }
  11. public void addChild(Node<T> child) {
  12. if (children.contains(child)) return;
  13. child.setParent(this);
  14. children.add(child);
  15. }
  16. public T getValue() {
  17. return value;
  18. }
  19. public Node<T> getParent() {
  20. return parent;
  21. }
  22. protected void setParent(Node<T> parent) {
  23. this.parent = parent;
  24. }
  25. public boolean hasParent() {
  26. return parent != null;
  27. }
  28. public LinkedList<Node<T>> getChildren() {
  29. return children;
  30. }
  31. public Node<T> getFirstChild() {
  32. return children.isEmpty() ? null : children.getFirst();
  33. }
  34. public Node<T> getLastChild() {
  35. return children.isEmpty() ? null : children.getLast();
  36. }
  37. public boolean isLastChild() {
  38. return hasParent() ? isTheLastChildOfParent() : false;
  39. }
  40. private boolean isTheLastChildOfParent() {
  41. return this.equals(getParent().getLastChild());
  42. }
  43. public int totalQuantityOfNodes() {
  44. int size = 1;
  45. for (Node<T> child : children) size += child.totalQuantityOfNodes();
  46. return size;
  47. }
  48. public void print(StringBuilder builder) {
  49. print(builder, "");
  50. }
  51. private void print(StringBuilder builder, String margin) {
  52. builder.append(margin).append("-").append(value.toString()).append("\n");
  53. for (Node<T> child : children) child.print(builder, margin + " ");
  54. }
  55. public T getParentValue() {
  56. return (getParent() != null) ? getParent().getValue() : null;
  57. }
  58. }