DEV Community

Ramya K
Ramya K

Posted on

Collection framework

  1. What is the difference between fail-fast and fail-safe iterators?

● Fail-fast (like in ArrayList, HashMap) throw ConcurrentModificationException if the collection is modified while iterating.
● Fail-safe (like in CopyOnWriteArrayList, ConcurrentHashMap) operate on a clone, so no exception is thrown.

🔹 2. Why does HashMap key need equals() and hashCode() methods?
Because keys are stored in buckets based on their hash code.
● hashCode() decides the bucket.
● equals() resolves collisions by comparing actual content.

🔹3. What happens if two keys have the same hash code in a HashMap?
They go into the same bucket as a linked list (or tree in Java 8+). HashMap then uses equals() to distinguish between them.

🔹 4. Can we insert null in a HashSet or HashMap?
● HashMap → one null key allowed, multiple null values allowed.
● HashSet → one null element allowed.
● Hashtable and ConcurrentHashMap → do not allow nulls.

🔹 5. How does HashMap handle rehashing?
When the load factor (default 0.75) is exceeded, it doubles the capacity and rehashes all entries into new buckets.

🔹 6. What’s the difference between ArrayList and LinkedList in terms of performance?
● ArrayList → faster for random access, slower for insert/delete in middle.
● LinkedList → faster for frequent insert/delete, slower for random access. But in practice, ArrayList is usually preferred due to lower memory overhead.

🔹 7. How does TreeMap maintain sorting?
It keeps entries sorted according to natural ordering or a custom Comparator. It uses a Red-Black Tree internally.

🔹 8. What is the difference between Collection and Collections?
● Collection → an interface (List, Set, Queue).
● Collections → a utility class with static methods like sort(), reverse(), shuffle(), etc.

🔹 9. What is the difference between HashMap and ConcurrentHashMap?
● HashMap→ not thread-safe, can cause data inconsistency.
● ConcurrentHashMap → thread-safe, divides map into segments, no locking of entire map.

🔹 10. Why compareTo() and equals() must be consistent in sorted collections like TreeSet or TreeMap?
Because if compareTo() says two objects are equal but equals() disagrees, it can break contract — leading to missing or duplicate elements in sorted collections.

Top comments (0)