All Downloads are FREE. Search and download functionalities are using the official Maven repository.

querqy.trie.TrieMap Maven / Gradle / Ivy

There is a newer version: 3.18.1
Show newest version
/**
 * 
 */
package querqy.trie;

import java.util.Iterator;
import java.util.NoSuchElementException;


/**
 * @author René Kriegler, @renekrie
 *
 */
public class TrieMap implements Iterable {
    
    Node root;
    
    public void put(CharSequence seq, T value) {
        int length = seq.length();
        if (length == 0) {
            throw new IllegalArgumentException("Must not put empty sequence into trie");
        }
        if (root == null) {
            synchronized (this) {
                if (root == null) {
                    root = new Node(seq.charAt(0));
                }
            }
        }
        
        root.put(seq, 0, value);
    }
    
    public Iterator iterator() {
        if (root == null) {
            return new Iterator() {

                @Override
                public boolean hasNext() {
                    return false;
                }

                @Override
                public T next() {
                    throw new NoSuchElementException();
                }
                
                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };
        } else {
            return root.iterator();
        }
    }
    
    public void putPrefix(CharSequence seq, T value) {
        int length = seq.length();
        if (length == 0) {
            throw new IllegalArgumentException("Must not put empty sequence into trie");
        }
        if (root == null) {
            synchronized (this) {
                if (root == null) {
                    root = new Node(seq.charAt(0));
                }
            }
        }
        
        root.putPrefix(seq, 0, value);
    }
    
    public States get(CharSequence seq) {
        if (seq.length() == 0) {
            return new States<>(new State(false, null, null));
        }
        return (root == null) ? new States<>(new State(false, null, null)) : root.get(seq, 0);
    }
    

    public States get(CharSequence seq, State stateInfo) {
        if (!stateInfo.isKnown()) {
            throw new IllegalArgumentException("Known state expected");
        }
        if (seq.length() == 0) {
            return new States<>(new State(false, null, null));
        }
        return stateInfo.node.getNext(seq, 0);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy