Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an item from a Java Set

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?

like image 290
Will Avatar asked Oct 01 '12 09:10

Will


2 Answers

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.

like image 62
Donald Raab Avatar answered Oct 13 '22 13:10

Donald Raab


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.

like image 33
Peter Lawrey Avatar answered Oct 13 '22 12:10

Peter Lawrey