I'm using a HashMap
to store a list of tags that are required in a certain message, for multiple messages, ie a HashMap<String,ArrayList<TagObject>>
. Each TagObject
has attributes, the main one is whether that tag is required or not in a certain message. Now, if a tag is required in one message, and not in another, the final required value ends up being the one that was processed last. I am also creating a HashMap<String,TagObject>
to store all the tags processed. Maybe that is causing the issue? I think the issue is the same variable gets overridden repeatedly, how do I make separate copies for each message to store in the main HashMap of messages?
I've looked up HashMap overridden by last value, but I am creating a new Field everytime, so this doesn't seem to be the reason.
for(TagObject o:allTags) {
if(o instanceof Field){
fieldResult=new Field();
Field field = (Field) o;
String required=field.getRequired(); //this is the value found in the file where the specifications are, ie whether the field should be required or no in this message. this value is received correctly
if(required == null || required.equalsIgnoreCase("yes")) {
required="true";
}else{
required="false";
}
else {
fieldResult=ctd.searchFieldMap(field.name); //find the already created Field object
fieldResult.setRequired(required); //set the required now as got from the specifications
}
fieldsInMessage.add(fieldResult); //add this field to list of fields to be there in the message
//while being added, I can see the value of the required tag go as in the specs, however when I later print the hashmap of all messages, the tag which was required in one message, but set as not required in another, has changed value to the value of required of the last appearance of the field in the specifications
}
}
I was hoping that a new copy of the field will be created for each message, but seems like the same object is used in all. How do I make sure each message can have a separate copy of the tag, and hence unique attributes?
Figured out what I really needed. I wanted to create a copy of a value in a HashMap, what I had been doing was copying over the reference to the object, which is why it kept getting overridden. What I really needed was a copy constructor. This helped: https://stackoverflow.com/a/33547834/1677804