I think the code is pretty easy to read. Just iterate over each and track if it is unique. If you want to track it, it returns true / false if it was added
Method testing
DefaultMutableTreeNode child = new DefaultMutableTreeNode("String"); DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("String"); DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("String1"); addUniqueNode(child, model);
Method:
public boolean addUniqueNode(DefaultMutableTreeNode childNode, DefaultTreeModel model) { DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); // Check each node boolean isUnique = true; for (int i = 0; i < model.getChildCount(root); i++) { Object compUserObj = ((DefaultMutableTreeNode) model.getChild(root, i)).getUserObject(); if (compUserObj.equals(childNode.getUserObject())) { isUnique = false; break; } } // If Unique, insert if(isUnique) model.insertNodeInto(childNode, root, root.getChildCount()); return isUnique; }
source share