CapgeminiRealTimeInterview
CapgeminiRealTimeInterview
always return `100`, it will have significant performance implications for the
`HashMap`. Here’s what happens:
---
2. **Collisions Increase**:
- A hash collision occurs when multiple keys map to the same bucket.
- In this case, every key will map to the bucket corresponding to hash code
`100`.
3. **Degraded Performance**:
- When retrieving or storing an entry, the `HashMap` first identifies the bucket
using the hash code.
- If all entries are in one bucket, the `HashMap` must iterate through all
entries in that bucket to find the correct one.
- **Time Complexity**:
- Ideal: `O(1)` (when the hash codes are well-distributed).
- Worst Case: `O(n)` (if all entries fall into one bucket, which happens
here).
---
class CustomKey {
private String value;
@Override
public int hashCode() {
return 100; // Same hash code for all keys
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
CustomKey that = (CustomKey) obj;
return value.equals(that.value);
}
}
public class Main {
public static void main(String[] args) {
HashMap<CustomKey, String> map = new HashMap<>();
map.put(new CustomKey("key1"), "value1");
map.put(new CustomKey("key2"), "value2");
map.put(new CustomKey("key3"), "value3");
---
2. **Retrieval**:
- For every retrieval, the `equals()` method is called for every object in the
bucket until a match is found.
---
Example:
```java
@Override
public int hashCode() {
return Objects.hash(value); // Generate hash code based on fields
}
```
---
---
---
Example:
```java
class CustomKey {
private String value;
map.put(key1, "value1");
---
---
---
---
Example:
```java
class CustomKey {
private String value;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
CustomKey that = (CustomKey) obj;
return value.equals(that.value);
}
@Override
public int hashCode() {
return Objects.hash(value); // Generate hash code using fields
}
}
map.put(key1, "value1");
System.out.println(map.get(key2)); // Output: value1
}
}
```
---
### **Conclusion**
If you don’t override `hashCode()`:
- The `HashMap` may behave incorrectly, especially if you override `equals()`.
- Objects that are logically equal will not work as expected when used as keys in a
hash-based collection.
To ensure correctness and maintain the `HashMap` contract, always override
`hashCode()` and `equals()` together.
=========================