Ran_Macavity
Ran_Macavity

Reputation: 154

ArrayList added item is replaced by the next item in for loop

I am facing a very strange situation. I add an object to an arrayList in a loop, but it is replaced by the next object. Actually second item is duplicated. ( It replaces the first item as well as inserts another object to the ArrayList.)

This is my code. I have done the debugging and included the comments where needed. Could someone point out why this happens? I am taking the object details from the database and those are working as expected.

public class Serv
{
    @Autowired
    GrpHeader objGrpHeader;

    @Autowired
    CompPesoOutgoingMsg objMsg;

    @Autowired
    OutwardMessage objOutwardMessage;

    public List<OutwardMessage> outgoingMessagesAsSingleTrx()
    {
        List<OutgoingMsg_Obj> trxList = myRepo.getTrx("5");
        List<OutwardMessage> myTrxList = new ArrayList<>();


        for (OutgoingMsg_Obj outgoingMsg : trxList)
        {
            BigDecimal trxAmt = outgoingMsg.getIntrBkSttlmAmt().getTrxn_amt();
            trxAmt = (trxAmt).divide(new BigDecimal(100));

            GrpHeader grpHeader = objGrpHeader;
            CompPesoOutgoingMsg outMsg2 = objMsg;
            OutwardMessage objOutwardMessage2 = objOutwardMessage;

            outgoingMsg.setRmtInf(objRmtInf);
            outgoingMsg.setPmtTpInf(objPmtTpInf);

            outMsg2.setHeader(grpHeader);
            outMsg2.setCdtTrfTxInf(Arrays.asList(outgoingMsg));
            objOutwardMessage2.setObjMsg(outMsg2);

            **//Here, Correct object details are printed**
            log.info("outwardMsg 100 {} ", objOutwardMessage2);

            //Add Item to the list
            myTrxList.add(objOutwardMessage2);

            for (OutwardMessage outwardMsgx : myTrxList)
            {
                //1. When this loop executed first time, first object details are printed
                //2. When printed second time, first added object is no more. And second added object is there twice.
                log.info("outwardMsg 101 {} ", outwardMsgx);
            }
        }
        return myTrxList;
    }
}

Upvotes: 3

Views: 486

Answers (2)

Sreejith
Sreejith

Reputation: 566

Since no new object is created for each iteration, the same objOutwardMessage2 value is getting replaced each time.

Try

OutwardMessage objOutwardMessage2 = new OutwardMessage();

and copy the value of objOutwardMessage to the newly created objOutwardMessage2.

Upvotes: 1

fjsv
fjsv

Reputation: 714

You have a single reference. By setting the objOutwardMessage2to objOutwardMessageyou are just changing the data inside the reference.

Upvotes: 1

Related Questions