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.

Upvotes: 6

Views: 3418

Answers (2)

dacwe
dacwe

Reputation: 43504

You could just implement the equals method like that:

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

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308149

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>());

Upvotes: 13

Related Questions