I have a Set
of expensive objects.
These objects have IDs and the equals
uses these IDs for equality.
These objects' type has two constructors; one for the expensive object, and one that just sets the ID.
So I can check if a particular ID is in the Set
using Set.contains(new Object(ID))
.
However, having determined the object is in the set, I cannot get the object instance in the set.
How can I get the exact object that the set contains?
Consider using the UnifiedSet
class in Eclipse Collections. It implements the Pool
interface in addition to Set
. Pool
adds Map
-like API for put and get. Pool
is more memory efficient than Map
since it doesn't reserve memory for values, only keys.
UnifiedSet<Integer> pool = UnifiedSet.newSet();
Integer integer = 1;
pool.add(integer);
Assert.assertSame(integer, pool.get(new Integer(integer)));
Note: I am a committer for Eclipse Collections.
If you want to get
from a collection you should use a Map.
(Note most Set implementations are wrappers for a Map)
Map<Key, Value> map = new ....
Value value = map.get(new Key(ID));
In your case, the key and value can be the same type but that is generally a bad idea as keys, like elements of a set, should be immutable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With