7) What are the advantages of using Interface type in collection ?
- We can switch the implementation without changing the code.
- It is easy to test our code with testing and mocking frameworks.
- We can use the most generalized interface for data exchange (enumerator instead of a list, if you only want to iterate over the values).
|Fixed length||Size of the Array can be grown based on the need.|
|Can't use Generics.||Can use Generics|
|Provides length variable which denotes length||Provides size() method to calculate size|
|Can store primitives||We can't store primitives|
9) Can you explain the difference between fail fast iterator and fail safe iterator ?
Fail fast iterator : This iterator throws "ConcurrentModificationException" when a thread iterating a collection realizes that the same collection is modified by another thread while under operation. Iterator identifies change in collection is by looking at it's modification count. Ex: HashMap
Fail safe iterator : If we are using fails safe iterator, the above scenario is handled and java doesn't throw the ConcurrentModificationException. To handle this scenario, iterator makes a clone of the collection and works on it. Ex: ConcurrentHashMap
10) Can you explain about concurrent modification exception ?
When two or more threads try to modify an object where concurrent modification is not permitted, java throws concurrent modification exception which is a runtime exception. This exception is thrown by fail fast iterators.
11) what is the difference between iterator and list iterator ?
|Only forward movement is allowed.||It can move backwards as well as forward while reading the elements.|
|While traversing we can't obtain the index at any point.||We can obtain the index at any point while traversing|
|We can only check the availability of the next element||We can check availability of previous and next element.|
|We can't modify element while traversing.||Elements can be modified while traversing.|
12) Explain the get() and put() logic in hashmap ?
- First, check for null in the key. If null, then key value pair will be store in 0'th position. Reason for that is, Hashcode for null is 0.
- Else, calculate hash code of key by calling hashcode() method
- Based on the returned hashcode, hashmap implementation goes to the bucket(Stores Key Value pair) who's identifier is matching the returned hashcode. Once bucket is identified, hashmap search the basket for a matching key using equals method. If it finds one, value will be updated
- If a matching key is not found in the basket, java creates a new Key-Value pair in the basket.
- First, use the key to get the hashcode.
- Go to the basket with matching identifier as hash code.
- Iterate using equals method to find the matching key in the basket and once key is identified, return value which is stored along with key.