The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.prefs  [18 examples] > Nodes  [7 examples]

e417. Finding a Preference in a Preference Tree

There is no efficient method for finding a key in a preference node. All the nodes must be traversed and checked for the presence of the key. This example implements such a method.

This example can be modified to find nodes that matched values rather than keys by replacing contains() with containsValue(), as defined in e407 Determining If a Preference Node Contains a Specific Value.

    // Find first occurrence
    Preferences prefs = findNode(Preferences.userRoot(), null, "key");
    
    // Find all occurrences
    prefs = findNode(Preferences.userRoot(), null, "key");
    while (prefs != null) {
        prefs = findNode(Preferences.userRoot(), prefs, "key");
    }
    
    // Traverses all the nodes from root depth-first.
    // Returns the first node that contains the specified key.
    // If start is non-null, the nodes are checked only after the
    // start node is encountered.
    // Returns null if not found.
    public static Preferences findNode(Preferences root, Preferences start, String key) {
        // For the implementation of contains,
        // see e406 Determining If a Preference Node Contains a Specific Key
        if (start == null && contains(root, key)) {
            // Found the key
            return root;
        }
    
        // The start node has been encountered so start checking from now on
        if (start != null && root.equals(start)) {
            start = null;
        }
    
        // Recursively check the child nodes
        try {
            String[] names = root.childrenNames();
            for (int i=0; i<names.length; i++) {
                Preferences n = findNode(root.node(names[i]), start, key);
                if (n != null) {
                    // Found the key
                    return n;
                }
            }
        } catch (BackingStoreException e) {
        }
    
        // Not found
        return null;
    }

 Related Examples
e411. Getting the Roots of the Preference Trees
e412. Creating a Preference Node
e413. Retrieving a Preference Node
e414. Removing a Preference Node
e415. Determining If a Preference Node Exists
e416. Retrieving the Parent and Child Nodes of a Preference Node

See also: Events    Importing and Exporting   


© 2002 Addison-Wesley.