开发者

Instance set in Java?

Java defines a Set interface where contains() is defined as following:

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

The Collection interface defines contains() as following:

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e开发者_开发百科)).

I need a Java 'instance set' where contains() is based on == and not equals(). In other words, a set of hard instances where two different objects A and B where A.equals(B) could coexist in this same set, since A!=B.

Is such an 'instance set' delivered in Java or in some public library? I can't find anything, but may be someone knows better on SO. If not, I'll implement it. Thanks.


There is no direct "instance set" in the JRE.

But there is an IdentityHashMap, which implements a "instance map" according to your terminology.

And there is a method called Collections.newSetFromMap() which can create a Set from an arbitrary Map implementation.

So you can easily build your own instance set like this:

Set<MyType> instanceSet = Collections.newSetFromMap(new IdentityHashMap<MyType,Boolean>());


You could just implement the equals method like that:

public boolean equals(Obect o) {
    return this == o;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜