I found this trie implementation from Code Review, it works perfectly, I already changed it somehow to fit my program's needs now I want to manipulate the find()
function so I can have the results in an array.
Thanks.
Here's the class code:
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class AutoComplete {
private final Map<Character, HashMap> root = new HashMap<Character, HashMap>();
private final Character END_CHARACTER = '$';
/**
* Will create an empty AutoComplete
*/
public AutoComplete() {}
/**
* Will create an AutoComplete filled from a Collection of String items
*
* @param items A Collection (Vector, List etc.) of String items
*/
public AutoComplete (Collection<String> items)
{
for (String s : items)
{
internalAdd(s);
}
}
/**
* Will create an AutoComplete filled from an array of String items
*
* @param items An array of String items
*/
public AutoComplete (String[] items)
{
for (String s : items){
internalAdd(s);
}
}
/**
* Will add a String to the AutoComplete
*
* @param item The String item to add
* @return Returns true if item is added, false if item already exists
*/
public boolean add(String item)
{
if (find(item) != null)
{
internalAdd(item);
return true;
}
else
{
return false;
}
}
/**
* Will return an array of Strings that start with the given prefix
*
* @param prefix The prefix to search for
* @return An array of Strings starting with the prefix. Will return null if nothing is found.
*/
public String[] find(String prefix)
{
Map<Character, HashMap> node = root;
for (int i = 0; i < prefix.length(); i++)
{
if (node.isEmpty())
{
return null;
}
Character character = prefix.charAt(i);
if (node.containsKey(character))
{
node = node.get(character);
}
else
{
return null;
}
}
// return found items as an array
}
private boolean internalAdd(final String s)
{
Map<Character, HashMap> node = root;
for (int i = 0; i < s.length(); i++)
{
Character character = s.charAt(i);
if(node.isEmpty() || !node.containsKey(character))
{
internalAdd(s.substring(i), node);
break;
}
node = node.get(character);
}
node.put(END_CHARACTER, new HashMap());
return true;
}
private void internalAdd(final String s, Map<Character, HashMap> node)
{
for (int i = 0; i < s.length(); i++)
{
Character character = s.charAt(i);
node.put(character, new HashMap());
node = node.get(character);
}
}
}
I changed the whole class, now it returns the found items in an array. Here is the class code: