Labeler

From Progteam

Revision as of 23:56, 19 October 2008 by Hjfreyer (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This is a handy inner class which can map a collection of objects (any objects) onto a set of numbers (0, X] where X is the number of items mapped. The map is bidirectional, but that isn't always needed.

Code

    static class Labeler<T> {
        int count = 0;
        Map<T, Integer> map = new HashMap<T, Integer>();
        List<T> list = new ArrayList<T>();

        public int get(T t) {
            if (!map.containsKey(t)) {
                map.put(t, count++);
                list.add(t);
            }
            return map.get(t);
        }

        public T reverse(int i) {
            return list.get(i);
        }
    }
Personal tools