Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a HashSet.contains() returning an Object

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?

like image 689
Roam Avatar asked Mar 02 '26 21:03

Roam


1 Answers

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.

like image 184
user2357112 supports Monica Avatar answered Mar 05 '26 12:03

user2357112 supports Monica