Suppose i'm working a type A in Collections.
class A {
ThisType thisField;
ThatType thatField;
String otherField;
}
Only thisField and thatField are relevant to identify the instances of A-- so its equals() and along with it hashCode() methods are overridden accordingly.
With this, in a HashSet<A> setOfAs, the objects of A are unique across their (thisField,thatField) value pair.
Somewhere in the application, i need to look up the Set for an instance of A and if it exists, print its otherField-- the meta-info.
i can
i.) get an iterator on setOfAs, see each entry for its thisField and thatField values, and if they both match, print its otherField
ii.) use a self-map, HashMap<A,A> selfMapA, where key and value are the same objects in each entry. instantiate A with (thisField,thatField) value pair to look-up selfMapA and get its matching entry as is if it's there.
(i) is O(n)-- doesn't get the object in constant time although it finds it in constant time.
(ii) gets the object in constant time and is what we keep using in the system. however, it's using twice the memory.
what i'm looking for is a set structure getting the object entry that it finds in constant time. for instance, one with a
contains(Object) method returning an Object, the object it found if it exists, rather than boolean as HashSet.contains() does.
are there better alternatives to these? is there a way to get around this?
HashSet is implemented using a HashMap with all values set to a dummy object, so option 2 should actually use slightly less memory than a HashSet. I would go with option 2.
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