Labeler

From Progteam

(Difference between revisions)
Jump to: navigation, search
(New page: 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'...)
 
Line 19: Line 19:
             return list.get(i);
             return list.get(i);
         }
         }
 +
    }
</pre>
</pre>
[[Category:Code Packet]]
[[Category:Code Packet]]

Latest revision as of 23:56, 19 October 2008

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