Mohit Gandhi
Mohit Gandhi

Reputation: 69

Why element of Java Hash map overrides the previous elements?

Suppose in Hash map of java collections has already a pair 0,"Ram" and I add a new pair 0,"Sham" with same key. I knew it override the value and at last we get the 0,"Sham" in hash set. My Questions is Why "Sham" i.e newer element override the "Ram" i.e. previous element? Is there any function to stop this overriding or I should use if-else conditions to make a check on it?

Upvotes: 1

Views: 76

Answers (1)

Anil Agrawal
Anil Agrawal

Reputation: 3026

You can write your own put method using delegation technique, if any value already present in map, ignore the calling of put and returns false status.

boolean putIfNotPresent(Map map, Object key, Object value){
    if(map.get(key)==null){
        map.put(key, value);
        return true;
    }else{
        return false;
    }
}

Why value is overridden by default :
Its all about use case of functionality. Java implemented the most common use-case. And there are options for any specific use-case .

Upvotes: 1

Related Questions