• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 161
  • Last Modified:

overriding entries in Map

hi guys

I have


public class CacheData{
private String id;
private String name;
private String key;

set() methods;
get() methods;

Open in new window

public class CacheImpl{
private void cacheImp{
String webserviceId = getWebserviceId(); //returns a uniqe webserviceId ;
Map<String,CacheData> cacheMap = new HashMap<String,CacheData>();
CacheData cdata = new CacheData();
cacheMap.put(webserviceId , cdata);
Map cache = construct(cacheMap);

private Map construct(Map cacheMap){
CacheData newCData = //make webserivice call and construct CacheData;
 cacheMap.put(webserviceId , newCData); //same webserviceId key is put again  the second time in cacheMap , So now does the cacheMap contain only one enrty 
with webserviceId  as the key and newCData as the value.
Does it override the 'put' which was made earlier?

}//end class

Open in new window

  • 3
1 Solution
mccarlIT Business Systems Analyst / Software DeveloperCommented:
The answer is: YES.

If you do multiple .put() calls with the same "key" value, then the earlier entries get "replaced" by the last one.
mccarlIT Business Systems Analyst / Software DeveloperCommented:
For example:
Map<String, String> testMap = new HashMap<String, String>();
testMap.put("abc", "123");
testMap.put("abc", "456");
testMap.put("abc", "789");

System.out.println("The map is: " + testMap);

Open in new window

The map will only have one entry, and it's value will be "789"
royjaydAuthor Commented:
Do i have to override the equals() and hashcode() in my CacheData class?

mccarlIT Business Systems Analyst / Software DeveloperCommented:
From just the above code... No. You can but it's not required. You are only using CacheData in as "values" in the map. If you were to use that class as the "key" to the map, then yes you should implement your own equals and hashcode.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now