从 Set 中检索“规范值”,其中 T 具有自定义 equals()

2024-03-27

我有一个class Foo这会覆盖equals() and hashCode()适当地。

我想也想使用HashSet<Foo>跟踪“规范值”,例如我有一堂课我会like像这样写,这样如果我有两个等效的独立对象,我可以将它们合并为对同一对象的引用:

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;
        }
    }
}

除了那个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);
        }
    }
}

Use an Interner来自番石榴:

http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Interner.html http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Interner.html

http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Interners.html http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Interners.html

这正是它的用途。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Set 中检索“规范值”,其中 T 具有自定义 equals() 的相关文章

随机推荐