package common.util;

import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;

import common.collect.Iterators;
import common.collect.Lists;

public class IdMap<T> implements Iterable<T> {
	private final IdentityHashMap<T, Integer> mapping = new IdentityHashMap(512);
	private final List<T> list = Lists.<T>newArrayList();

	public void put(T key, int value) {
		this.mapping.put(key, value);
		while(this.list.size() <= value) {
			this.list.add(null);
		}
		this.list.set(value, key);
	}

	public int get(T key) {
		Integer i = this.mapping.get(key);
		return i == null ? -1 : i.intValue();
	}

	public final T getByValue(int value) {
		return value >= 0 && value < this.list.size() ? this.list.get(value) : null;
	}

	public Iterator<T> iterator() {
		return Iterators.filter(this.list.iterator(), Predicates.notNull());
	}
}
