patternjavaModerate
Building a simple tree structure
Viewed 0 times
simplestructurebuildingtree
Problem
I'm trying to build this simple tree:
I came up with this simple method which recursively walk a tree:
Is there a better way or more elegant way to do this?
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
You didn't need this cast:
because you correctly declared the iterator as
As of Java 1.5, you can use a for-each loop, which is simple and elegant:
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 itrAs 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.