是的,使用HashMap ...但以一种特殊的方式:我预见到尝试将HashMap用作伪Set的陷阱是@987654324的“实际”元素之间可能存在混淆@ 和“候选”元素,即用于测试equal 元素是否已经存在的元素。这远非万无一失,但可以让你远离陷阱:
class SelfMappingHashMap<V> extends HashMap<V, V>{
@Override
public String toString(){
// otherwise you get lots of "... object1=object1, object2=object2..." stuff
return keySet().toString();
}
@Override
public V get( Object key ){
throw new UnsupportedOperationException( "use tryToGetRealFromCandidate()");
}
@Override
public V put( V key, V value ){
// thorny issue here: if you were indavertently to `put`
// a "candidate instance" with the element already in the `Map/Set`:
// these will obviously be considered equivalent
assert key.equals( value );
return super.put( key, value );
}
public V tryToGetRealFromCandidate( V key ){
return super.get(key);
}
}
然后这样做:
SelfMappingHashMap<SomeClass> selfMap = new SelfMappingHashMap<SomeClass>();
...
SomeClass candidate = new SomeClass();
if( selfMap.contains( candidate ) ){
SomeClass realThing = selfMap.tryToGetRealFromCandidate( candidate );
...
realThing.useInSomeWay()...
}
但是...您现在希望candidate 以某种方式自毁,除非程序员实际上立即将其放入Map/Set...您希望contains“污染”@987654331 @ 所以除非它加入Map,否则任何使用它都会使其成为“诅咒”。也许你可以让SomeClass 实现一个新的Taintable 接口。
更令人满意的解决方案是 GettableSet,如下所示。但是,要使其工作,您必须负责 SomeClass 的设计,以使所有构造函数不可见(或者......能够并愿意为其设计和使用包装类):
public interface NoVisibleConstructor {
// again, this is a "nudge" technique, in the sense that there is no known method of
// making an interface enforce "no visible constructor" in its implementing classes
// - of course when Java finally implements full multiple inheritance some reflection
// technique might be used...
NoVisibleConstructor addOrGetExisting( GettableSet<? extends NoVisibleConstructor> gettableSet );
};
public interface GettableSet<V extends NoVisibleConstructor> extends Set<V> {
V getGenuineFromImpostor( V impostor ); // see below for naming
}
实施:
public class GettableHashSet<V extends NoVisibleConstructor> implements GettableSet<V> {
private Map<V, V> map = new HashMap<V, V>();
@Override
public V getGenuineFromImpostor(V impostor ) {
return map.get( impostor );
}
@Override
public int size() {
return map.size();
}
@Override
public boolean contains(Object o) {
return map.containsKey( o );
}
@Override
public boolean add(V e) {
assert e != null;
V result = map.put( e, e );
return result != null;
}
@Override
public boolean remove(Object o) {
V result = map.remove( o );
return result != null;
}
@Override
public boolean addAll(Collection<? extends V> c) {
// for example:
throw new UnsupportedOperationException();
}
@Override
public void clear() {
map.clear();
}
// implement the other methods from Set ...
}
您的NoVisibleConstructor 类如下所示:
class SomeClass implements NoVisibleConstructor {
private SomeClass( Object param1, Object param2 ){
// ...
}
static SomeClass getOrCreate( GettableSet<SomeClass> gettableSet, Object param1, Object param2 ) {
SomeClass candidate = new SomeClass( param1, param2 );
if (gettableSet.contains(candidate)) {
// obviously this then means that the candidate "fails" (or is revealed
// to be an "impostor" if you will). Return the existing element:
return gettableSet.getGenuineFromImpostor(candidate);
}
gettableSet.add( candidate );
return candidate;
}
@Override
public NoVisibleConstructor addOrGetExisting( GettableSet<? extends NoVisibleConstructor> gettableSet ){
// more elegant implementation-hiding: see below
}
}
PS 一个与 NoVisibleConstructor 类有关的技术问题:可能会反对这样一个类本质上是 final,这可能是不可取的。实际上,您总是可以添加一个虚拟的无参数 protected 构造函数:
protected SomeClass(){
throw new UnsupportedOperationException();
}
... 这至少可以让子类编译。然后您必须考虑是否需要在子类中包含另一个 getOrCreate() 工厂方法。
最后一步是一个抽象基类(NB“元素”用于列表,“成员”用于集合)对于您的集合成员(如果可能 - 同样,使用 包装类,其中该类不在您的控制之下,或者已经有一个基类等),以最大限度地隐藏实现:
public abstract class AbstractSetMember implements NoVisibleConstructor {
@Override
public NoVisibleConstructor
addOrGetExisting(GettableSet<? extends NoVisibleConstructor> gettableSet) {
AbstractSetMember member = this;
@SuppressWarnings("unchecked") // unavoidable!
GettableSet<AbstractSetMembers> set = (GettableSet<AbstractSetMember>) gettableSet;
if (gettableSet.contains( member )) {
member = set.getGenuineFromImpostor( member );
cleanUpAfterFindingGenuine( set );
} else {
addNewToSet( set );
}
return member;
}
abstract public void addNewToSet(GettableSet<? extends AbstractSetMember> gettableSet );
abstract public void cleanUpAfterFindingGenuine(GettableSet<? extends AbstractSetMember> gettableSet );
}
...用法相当明显(在您的SomeClass 的static 工厂方法中):
SomeClass setMember = new SomeClass( param1, param2 ).addOrGetExisting( set );