Q. How HashMap works in Java ?
The HashMap requires a hash function and uses hashCode and equals methods, in order to put and retrieve elements to and from the collection respectively.
When the put method is invoked, the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection.
If the key exists, its value is updated with the new value.
Q. Array vs. ArrayList
- Arrays can contain primitive or objects, while an ArrayList can contain only objects.
- Arrays have fixed size, while an ArrayList is dynamic.
- An ArrayList provides more methods and features, such as addAll, removeAll, iterator, etc.
Q. Enumeration vs. Iterator interfaces
- Enumeration is twice as fast as compared to an Iterator and uses very less memory.
- Iterator is much safer compared to Enumeration, because other threads are not able to modify the collection object.
- Iterators allow the caller to remove elements from the underlying collection, which is not possible in Enumerations.
Q. HashSet vs. TreeSet
- HashSet is implemented using a hash table and thus, its elements are not ordered.
The add, remove, and contains methods of a HashSet have constant time complexity O(1)
- TreeSet is implemented using a tree structure.
The elements in a TreeSet are sorted, and thus, the add, remove, and contains methods have time complexity of O(log n)
Q. What is PriorityQueue ?
The PriorityQueue is an unbounded queue, based on a priority heap and its elements are ordered in their natural order.
It doesn’t allow null values.
It is not thread-safe and it requires O(log(n)) time for its enqueing and dequeing operations.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.