akshay Sharma
akshay Sharma

Reputation: 57

How is traversal is working on hashsets and hashmaps?

I realize we can use a for loop to iterate over elements of hashset. e.g.

Set set = new HashSet();

for(Object object : set) {
    String element = (String) object;
}

I am not able to figure out how it internally works?

It makes sense in case of arrayList because elements are stored one after the another. So iterator has the reference to first value and then we can use hasNext() and next() to iterate over all the elements. But in case of hashsets and hashmaps how does it work?

What chatgpt/gemini replied:

When we create a hashset/hashmap buckets are assigned that are mapped to hashcodes. Lets say collision techniques are also in place. When we iterate, iterator go over all the buckets fetch the elements and then performs an equality check. It compares the retrieved element with the original elements you added using the equals() method.

It kind of makes sense, but I didn't get this equality check part. Why is this required? I assume these assigned buckets are exclusive to the hashset, so why not printing all the elements in bucket?

Upvotes: 0

Views: 41

Answers (0)

Related Questions