HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Building a simple tree structure

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simplestructurebuildingtree

Problem

I'm trying to build this simple tree:

Multiverse
|
|--- Universe
|
|--- Supercluster
|
|--- Galaxy
|
|--- Andromeda
|
|--- Milky way


I came up with this simple method which recursively walk a tree:

/**
* recursively walk a tree structure
*/
public static void recursive(TreeViewItem treeNode){

System.out.println(treeNode.getText());

Iterator itr = treeNode.getItems().iterator();

while (itr.hasNext()) {
TreeViewItem item = (TreeViewItem) itr.next();
recursive(item);
}
}


Is there a better way or more elegant way to do this?

Solution

You're visiting and printing the tree elements in a depth-first manner, so depthFirstPrint would be a much better name than "recursive" (which is always a terrible name for any recursive function).

You didn't need this cast:

TreeViewItem item = (TreeViewItem) itr.next();


because you correctly declared the iterator as Iterator itr

As of Java 1.5, you can use a for-each loop, which is simple and elegant:

for (TreeViewItem item : treeNode.getItems()) {
    depthFirstPrint(item);
}

Code Snippets

TreeViewItem item = (TreeViewItem) itr.next();
for (TreeViewItem item : treeNode.getItems()) {
    depthFirstPrint(item);
}

Context

StackExchange Code Review Q#63105, answer score: 10

Revisions (0)

No revisions yet.