简体   繁体   中英

adding arraylist object in iterator while loop causes second object to over write one object

I have an arraylist which is iterated using an iterator. the iterated data is passed to a method getDetails as a parameter. now the method returned data is written to an arraylist detailsList. So if the arraylist DTOList has two different objects, the second object is over writing the first one. So when i read the list, it has two same object contents.

List < BRType > detailsList= new ArrayList < BRType > ();
        List < RDTO > rDTOList = crList;
        List < ADTO > aDTOList = daList;
        Iterator < RDTO > rDTOIterator = rDTOList.iterator();
         Iterator < ADTO > aDTOIterator = aDTOList.iterator();
        while (rDTOIterator.hasNext() && aDTOIterator.hasNext()) {
            RDTO rDTO = rDTOIterator.next();
            ADTO aDTO = aDTOIterator.next();

        detailsList.add(getDetails(rDTO , aDTO , bookingRuleType,null));
    }

here during the first while loop the detailsListhas the code of 1, and during second run it has 2 . so when i run the below code i get 2 and 2

  for(BRType d : detailsList){
                System.out.println(d.getCode());

            }

I got it!!! it was a small mistake. in this method call

getMarCancelPolicyDepositRuleBySWCancelPolicyDepositRule(cancelDepositRuleDTO, cancelDepositAmountDTO, bookingRuleType,null)

the bookingRuleType parameter to the method, that object reference was created outside the while loop. so i put this BookingRuleType bookingRuleType = new BookingRuleType(); inside the while loop and it worked like charm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM