从Set <T>中检索"规范值",其中T具有自定义等于()

Jas*_*n S 2 java set

我有一个class Foo覆盖equals()hashCode()正确.

我想也想用一个HashSet<Foo>跟踪"规范值",例如我有,我会一类喜欢写这样的,所以,如果我有一个是等价的两个不同的对象,我可以合并他们进入到引用同一个对象:

class Canonicalizer<T>
{
    final private Set<T> values = new HashSet<T>(); 

    public T findCanonicalValue(T value)
    {
        T canonical = this.values.get(value);
        if (canonical == null)
        {
           // not in the set, so put it there for the future
           this.values.add(value);
           return value;
        }
        else
        {
           return canonical;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

除了Set没有"get"方法,它将返回存储在集合中的实际值,只返回返回true或false的"contains"方法.(我猜它假设如果你的对象等于集合中的单独对象,你不需要检索集合中的对象)

有没有方便的方法来做到这一点?我唯一能想到的是使用地图和列表:

class Canonicalizer<T>
{
    // warning: neglects concurrency issues

    final private Map<T, Integer> valueIndex = new HashMap<T, Integer>(); 
    final private List<T> values = new ArrayList<T>();

    public T findCanonicalValue(T value)
    {
        Integer i = this.valueIndex.get(value);
        if (i == null)
        {
           // not in the set, so put it there for the future
           i = this.values.size();
           this.values.add(value);
           this.valueIndex.put(value, i);
           return value;
        }
        else
        {
           // in the set
           return this.values.get(i);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)