Java instance set?

Java defines the Set interface, where contains() is defined as follows:

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 follows:

Returns true if this collection contains the specified item. More formally, it 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 set of Java instances where contains() based on == , not equals() . In other words, a set of hard instances, where two different objects are A and B, where A.equals(B) can coexist in the same set, since A!=B

Is such a โ€œset of instancesโ€ shipped in Java or in some public library? I canโ€™t find anything, but maybe someone knows better. If not, I will implement it. Thanks.

+6
source share
2 answers

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

But there is an IdentityHashMap that implements an "instance map" according to your terminology.

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

So you can easily create your own instance, for example:

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

You can simply implement the equals method as follows:

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

Source: https://habr.com/ru/post/896623/


All Articles