querqy.trie.TrieMap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of querqy-core Show documentation
Show all versions of querqy-core Show documentation
Querqy library for query rewriting: Querqy Core
/**
*
*/
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);
}
}