Java Collections Interview Questions

Java Collections Interview Questions

1. List versus Set in Collection framework?

  • List have elements of same type entered in ordered form and allows duplicate elements.
  • Set have non-duplicate elements added in ordered form.

2. Which collection maintains insertion order while adding elements?

  • LinkedHashSet and LinkedHashMap
  • LinkedHashSet uses a LinkedHashMap to store its elements. LinkedHashMap used doubly linked list internally that connects all its entries. This LinkedList defines the iteration ordering, which is the order in which the elements were inserted into the Set.

3. What is the contract between Hash code and Equals?

  • If objects are equal they must have the same hash code.
  • if obj1.equals(obj2) returns true, then obj1.hashCode() must be equal to obj2.hashCode().
  • If two objects have same hash code they are not necessarily equal.
  • If obj1.hashCode() is equal to obj2.hashCode(), obj1.equals(obj2) may return false. This scenario is called a “hash collision.”
  • Consistency
  • The hash code and equals method should return the same value w.r.t the object during entire compilation if object is not modified.

4. Explain HashMap versus Concurrent HashMap ?

5. Internal working of HashMap and Concurrent Hash Map ?

  • HashMap: It stores key-value pairs in the array of buckets, to promote fast retrieval of elements based on the key.
  • Hashing: The index of the bucket is calculated using the key of the pair, where the key-value pair has to be stored.
  • Hash Collision: There can be scenarios where multiple key-value pairs have same hash code, then these pairs are stored in the same bucket using chaining either in LinkedList or BST(post JAVA 8 if the length of linked list is increased).
  • Resize operation : If the Load factor is >= 0.75 then hash map resizes itself, by creating a new array with double the capacity.
  • Get operation: Elements are retrieved from hash map based on the key provided and key present at the particular hash code.
  • Internal working of Concurrent Hash Map: It uses multiple segments, each behaving like independent Hash map, Each segment had its lock so multiple threads could update different threads concurrently without interfering with each other. For read operations it allows fully concurrent access without locking, while writes only lock the necessary bucket.

6. What happens if we have to add new element in HashSet and that has hash code same as the existing element ?

  • It will internally check w.r.t the hash code the value of the object if equal to the existing object then it will be duplicate and it will not be added into the set,
  • If not equal then this element will be added in the same bucket as the existing element.

7. What happens if read thread wants to read data from concurrent hash map when write operation is performed by some thread?

  • Read thread will read previous value if the update has not been completed.
  • It will read the updated value if update has been done.

8. What is the difference between Hash Table and HashMap?

9. How to handle hash collision in java in case of hash map and what different we can do in java 8 why was this change required ?

  • Hash Collision Occurs when same key-value pairs have same hash code but keys for these pairs are not same then in the same hash code bucket both the pairs have to be accommodated. Then we store these values in Linked List but post Java 8 this has been stored in Red-Black (self-balancing Binary trees) once the number of entries exceed threshold.
  • If the number of entries increases then lookup, insertion and deletion is O(n) while in BST it is O(logn).

10. How can we make HashMap thread safe?

  • Downside of using above approach: Entire map is locked which can lead to contention and performance issues in high-concurrency scenarios.

11. Default number of threads in concurrent HashMap and how can it be increased?

  • It is not managed by ConcurrentHashMap, It totally depends on the application which uses Concurrent Hash Map.

12. How many threads can acquire lock in concurrent HashMap?

  • Multiple threads can access different buckets in parallel, but only one thread can modify the data in a single bucket at a time.

Note: Collection Framework Interview Question ->

https://www.geeksforgeeks.org/java-collections-interview-questions/

Tan Tran Minh

?Presales Assistant @ SoftwareOne | Modern Work & Security, Data Engineering

5 个月

Thanks for sharing bro !!!

Nhu Pham Nguyen To

Technical Recruiter - FPT Software. I'm urgently looking for Java, Automation Test, PM, BrSE, QA/QC talents.

6 个月

Are you ready for a new opportunity L?c ?i? I have some good news for ya

Ph?m H?ng

? Backend Developer

6 个月

Great advice

要查看或添加评论,请登录

Steve Loc的更多文章

  • Understanding and Implementing BRIN Indexes in PostgreSQL

    Understanding and Implementing BRIN Indexes in PostgreSQL

    1. Introduction to BRIN Indexes BRIN (Block Range Index) is a built-in index type in PostgreSQL designed for handling…

  • Best Practices and Pitfalls in Java Exception Handling

    Best Practices and Pitfalls in Java Exception Handling

    In Java programming, exception handling is essential for creating robust and error-resilient applications. By…

  • Introduce about Table-Level Locks in PostgreSQL

    Introduce about Table-Level Locks in PostgreSQL

    PostgreSQL employs diverse lock modes to manage concurrent data access in tables, complementing Multi-Version…

  • 4 SQL Phenomena and How to avoid it in Postgresql

    4 SQL Phenomena and How to avoid it in Postgresql

    Explanation of Four SQL Phenomena When dealing with concurrent transactions in a relational database, certain issues…

  • PostgreSQL Temporary Table

    PostgreSQL Temporary Table

    Summary: in this tutorial, you will learn about the PostgreSQL temporary table and how to manage it effectively…

    3 条评论
  • Parallel Processing in PostgreSQL: Setup, How It Works, and Use Cases

    Parallel Processing in PostgreSQL: Setup, How It Works, and Use Cases

    PostgreSQL’s parallel processing allows queries to run faster by distributing work across multiple CPU cores. This…

  • Avoiding Null Checks in Java with Optional

    Avoiding Null Checks in Java with Optional

    The NullPointerException (NPE) in Java is one of the most common runtime errors that developers face. It occurs when…

  • What Is Mutable Objects, How It Works In Java

    What Is Mutable Objects, How It Works In Java

    In previous article, I explained about Immutable Objects in Java. Today I will talk about Mutable Objects Let remember…

    1 条评论
  • Immutable Objects in Java

    Immutable Objects in Java

    In Java, understanding the difference between immutable and mutable objects is key to writing effective code. Immutable…

  • Database Replication

    Database Replication

    Database replication can be used in many database management systems, usually with a master/slave relationship between…

    2 条评论

社区洞察

其他会员也浏览了