Question

I know that this question has been asked here: Java tree data-structure?

But what is the best practice in implementing a tree in Java? The second most voted answer in the question linked above mentions TreeModel, but in the comments someone says that it isn't good coding practice to do so. Does this hold any truth? (I don't understand swing vs non-swing) Is using TreeModel common practice?

Was it helpful?

Solution

The comment you refer to says:

I would avoid using Swing libraries on non-Swing-related functions. This is bad coding practice. You never know how Swing implements their trees, what their dependencies are and how this could change in the future. Swing is not a utility library but a UI library.

In my experience, Swing is a sophisticated UI toolkit, but all of the model classes, like TreeModel or TableModel are tailored for the purpose of supporting a cross-plattform UI. Maybe the name model suggests that these encapsulate independent inner workings of those data structures - but the existence of classes like the ButtonModel tell me, that all these classes are more there for support of the MVC model.

From the docs:

Why then do models exist? The biggest reason is that they give you flexibility in determining how data is stored and retrieved. For example, if you're designing a spreadsheet application that displays data in a sparsely populated table, you can create your own table model that is optimized for such use.

OTHER TIPS

The TreeModel and TreeNode is for implementing the model of Swing's visual Tree component. You can see this on their packages javax.swing.tree for example. You should only use them for what they were designed (UI-related stuff, see Javadocs) and don't use them as a data structure. That is what this comment tells which you have mentioned. And this is absolutely correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top