Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Simple CharMap based on a Radix binary tree (See related posts)

Very simple Java implementation of a map from characters to objects based on a radix tree.

It's not actually that fast, as I've not bothered to optimise it at all (a brief attempt didn't work very well and I lost interest after that). It seems to be a little slower than a HashMap using boxed Characters and a little faster than a TreeMap (when the JIT gets up to speed anyway. Before the JIT has done any optimisation the hashmap is 2 or 3 times faster). I might at some point implement a HashMap using unboxed characters for keys to see what kind of performance improvement it gives.

Using a large array is of course faster than all of the options by an order of magnitude, but has the downside of being a bit too large to be useful. :-)

public class RadixCharMap<T>
{
    private RadixCharMap<T> map0; 
    private RadixCharMap<T> map1;
    private T value;
    
    private RadixCharMap<T> getMap(int i){
        if (i > 0) return map1 == null ? (map1 = new RadixCharMap<T>()) : map1;
        else return map0 == null ? (map0 = new RadixCharMap<T>()) : map0;}    
    
    public RadixCharMap<T> put(char key, T value){
        if (key == '\0') this.value = value;
        else getMap(key & 1).put((char)(key >> 1), value);
        return this;}
    
    public T get(char key){
        RadixCharMap current = this;
        if (key == '\0') return this.value;
        else return getMap(key & 1).get((char)(key >> 1));}
}

You need to create an account or log in to post comments to this site.


Click here to browse all 5137 code snippets

Related Posts