1 package pl.polidea.treeview;
3 import java.io.Serializable;
4 import java.util.LinkedList;
8 * Node. It is package protected so that it cannot be used outside.
11 * type of the identifier used by the tree
13 class InMemoryTreeNode<T> implements Serializable {
14 private static final long serialVersionUID = 1L;
16 private final T parent;
17 private final int level;
18 private boolean visible = true;
19 private final List<InMemoryTreeNode<T>> children = new LinkedList<InMemoryTreeNode<T>>();
20 private List<T> childIdListCache = null;
22 public InMemoryTreeNode(final T id, final T parent, final int level,
23 final boolean visible) {
28 this.visible = visible;
31 public int indexOf(final T id) {
32 return getChildIdList().indexOf(id);
36 * Cache is built lasily only if needed. The cache is cleaned on any
37 * structure change for that node!).
39 * @return list of ids of children
41 public synchronized List<T> getChildIdList() {
42 if (childIdListCache == null) {
43 childIdListCache = new LinkedList<T>();
44 for (final InMemoryTreeNode<T> n : children) {
45 childIdListCache.add(n.getId());
48 return childIdListCache;
51 public boolean isVisible() {
55 public void setVisible(final boolean visible) {
56 this.visible = visible;
59 public int getChildrenListSize() {
60 return children.size();
63 public synchronized InMemoryTreeNode<T> add(final int index, final T child,
64 final boolean visible) {
65 childIdListCache = null;
66 // Note! top levell children are always visible (!)
67 final InMemoryTreeNode<T> newNode = new InMemoryTreeNode<T>(child,
68 getId(), getLevel() + 1, getId() == null ? true : visible);
69 children.add(index, newNode);
74 * Note. This method should technically return unmodifiable collection, but
75 * for performance reason on small devices we do not do it.
77 * @return children list
79 public List<InMemoryTreeNode<T>> getChildren() {
83 public synchronized void clearChildren() {
85 childIdListCache = null;
88 public synchronized void removeChild(final T child) {
89 final int childIndex = indexOf(child);
90 if (childIndex != -1) {
91 children.remove(childIndex);
92 childIdListCache = null;
97 public String toString() {
98 return "InMemoryTreeNode [id=" + getId() + ", parent=" + getParent()
99 + ", level=" + getLevel() + ", visible=" + visible
100 + ", children=" + children + ", childIdListCache="
101 + childIdListCache + "]";