Câu hỏi phỏng vấn Java
Câu hỏi

What is the difference between HashMap , LinkedHashMap and TreeMap in Java?

Câu trả lời

In Java, HashMap, LinkedHashMap, and TreeMap are all implementations of the Map interface, which maps keys to values. Each of these classes has distinct characteristics that make them suitable for different use cases based on their internal data structures and the order in which they store the keys.

HashMap

  • Data Structure: HashMap is implemented using a hash table. It hashes the keys using the key’s own hashCode() method and stores them in an array-like structure.
  • Ordering: It does not maintain any order of the keys or values. The order of elements can appear random and can change when the map is resized.
  • Null Values: It allows one null key and multiple null values.
  • Performance: Offers constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. This is typically O(1).
  • Use Case: It is generally used when there is no requirement for ordering in the map and when performance is a critical factor[1][2][3][4].

LinkedHashMap

  • Data Structure: LinkedHashMap extends HashMap and thus inherits its hash table structure but also contains a doubly-linked list running through its entries.
  • Ordering: Maintains the order of elements as they are inserted into the map. If access order is specified in the constructor, it can also maintain elements in the order in which they were last accessed.
  • Null Values: Like HashMap, it allows one null key and multiple null values.
  • Performance: LinkedHashMap maintains insertion order at the cost of slightly higher memory overhead due to the linked list. The performance of basic operations remains similar to HashMap.
  • **Us...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What is the purpose of Garbage Collection in Java, and when is it used?

middle

Explain the role of Driver in JDBC.

entry

What is JVM? Why is Java called the "Platform Independent Programming Language"?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào