0

I want to implement a tree structure. Each node in the tree contains an object of my choosing, and a link to each of each children, and possibly parents. I am wondering if something like this exists in Java, so for example:

T randomObject = new randomObject();
Node<T> root;
root.setObject(randomObject);
root.addChild( ... 
....
root.getFirstChild().getObject().getObjectProperty();

I have looked into Node structure (org.w3c.dom.Node), but it does not seem to be able to store objects and seems more for parsing a document.

I also looked into things like DefaultMutableTreeNode, MutableTreeNode, and TreeNode, but I have not been able to find clear examples of usage. I encounter a lot of problems with these. For example, when passing a DefaultMutableTreeNode as a parameter (does not seem to work), or when getting the child of a DefaultMutableTreeNode, which seems to return simply a TreeNode, when I clearly have added DefaultMutableTreeNode as a child.

I am new to Java so any information would be very helpful. The Oracle documentation is not that helpful. I have worked with the Vector structure, which is very easy to work with, can store objects and is easily accesible, and am wondering if something similar may exist. Thanks.

2
  • 2
    Well, a TreeMap is a Map backed by a Red-Black Tree. Exactly what kind of Tree are you trying to build? Commented Jun 27, 2014 at 3:08
  • To my knowledge Java doesnt come with a premade implementation of a tree data structure in that fashion. However there are plenty of good ones online and its easy to make or modify one found online. See Google results for "java tree implementation": google.com/… Commented Jun 27, 2014 at 3:14

2 Answers 2

1

Check out https://github.com/poshjosh/bcuitreebuilder

A light weight java library for building TreeNodes from Documents, Files etc

public class ReadMe {

    public static void main(String [] args) {

        TreeBuilderFactory treeBuilderFactory = new TreeBuilderFactoryImpl();

        // For displaying each JTree
        //
        JScrollPane scrollPane  = new JScrollPane();
        scrollPane.setBounds(0, 0, 300, 300);

        // DocumentTreeBuilder 
        //
        Document doc = loadDocument(
             new File(System.getProperty("user.home")+"/Documents/Desktop/welcome.xml"));

        DOMTreeBuilder domTreeBuilder = treeBuilderFactory.getDOMInstance();

        Filter<Node> nodeFilter = null; // May be null

        TreeNode docRootNode = domTreeBuilder.build(doc, nodeFilter);

        JTree documentTree = new JTree(docRootNode);

        // Display the JTree
        //
        scrollPane.setViewportView(documentTree);
        JOptionPane.showMessageDialog(null, scrollPane);


        // FileTreeBuilder
        //
        File dir = new File(System.getProperty("user.home")+"/Documents");

        TreeBuilder<File> fileTreeBuilder = 
                 treeBuilderFactory.getInstance(TreeBuilderFactory.FILE);
        // This also works
        //FileTreeBuilder fileTreeBuilder = treeBuilderFactory..getFileInstance(); 

        Filter<File> fileFilter = new Filter<File>() {
            @Override
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().endsWith(".docx");
            }
        };

        TreeNode fileRootNode = fileTreeBuilder.build(dir, fileFilter);

        JTree fileTree = new JTree(fileRootNode);

        // Display the JTree
        //
        scrollPane.setViewportView(fileTree);
        JOptionPane.showMessageDialog(null, scrollPane);


        // MapTreeBuilder
        //
        MapTreeBuilder mapTreeBuilder = treeBuilderFactory.getMapInstance();

        final HashMap map = new HashMap();
        map.put("boolean", Boolean.TRUE);
        map.put("number", 100);
        map.put("List", new String[]{"1", "2", "3"});
        HashMap grandChildren = new HashMap();
        grandChildren.put("grandChild", "I am a grand child");
        map.put("hasChildren", grandChildren);

        Map.Entry rootEntry = mapTreeBuilder.createRootEntry(map);

        TreeNode mapRootNode = mapTreeBuilder.build(rootEntry, null);

        JTree mapTree = new JTree(mapRootNode);

        // Display the JTree
        //
        scrollPane.setViewportView(mapTree);
        JOptionPane.showMessageDialog(null, scrollPane);
    }

    private static Document loadDocument(File file) {
        Document doc;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            doc = docBuilder.parse(file);
        }catch (SAXException | IOException | ParserConfigurationException e) {
            e.printStackTrace();
            doc = null;
        }
        return doc;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I wanted something similar a few days back. This is what I did:

public class MyTreeNode extends DefaultMutableTree{
  //add all your objects here
}

DefaultMutableTree has predefined methods like add() -> to add child, it uses enumeration and provides standard methods to access child nodes using preorder and postorder processing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.