简体   繁体   中英

Adding objects in ArrayList in iteration

Ok, I don't know why but I am thinking I am missing something very basic to solve this. Here is my problem: I have a method createPublisherRequestObject(String str) which takes string argument and returns a List of ReportRequest Object. Normally for a given String 65 objects will be created. I have another method getTimeFrameValues() which returns arraylist of string. Normally this method would return around 15 strings in arraylist. So basically I would be iterating in loop for 15 times (Num of String) and then for each iteration, I will be calling method createPublisherRequestObject to create 65 objects. At the end of this I wanted to have a list of 65*15 objects. Here is my code -

ArrayList<String> timeList = er.getTimeFrameValues();
List<ReportRequest> reqList = new ArrayList<>();
for (Iterator iterator = timeList.iterator(); iterator.hasNext();) {
    String string = (String) iterator.next();
    reqList = rj.createPublisherRequestObject(string);
}
log.info("Final List Size "+reqList.size());

But this returns 65

Please help!!!

Thanks, pratik

Every time you go through the list, you're replacing reqList . It seems that what you're wanting to do is either reqList.add or reqList.addAll .

Additionally, if you already know how many objects you're creating per string, you'll get a lot better performance by creating an ArrayList of the appropriate size:

new ArrayList<>(65 * timeList.size())

Finally, since you're using Java 7, go ahead and use the enhanced for loop; it's much more readable:

for(String string: timeList)
    reqList.addAll(rj.createPublisherRequestObject(string));

You're reassigning to reqList on every iteration. You need to append.

reqList.addAll(rj.createPublisherRequestObject(string));

Should work.

You have 65 because you replace your reqlist with the result of the call to rj.createPublisherRequestObject(string) instead of using the addAll() method. So you don't add the elements but overwrite the content of reqlist. Therefore at the end the list have been overwritten 15 times and only contains 65 elements...

String string = (String) iterator.next();
reqList = rj.createPublisherRequestObject(string);

here you are assigning the result got from rj.createPublisherRequestObject(String) to reqList , so at end of itteration you have the last reurned value.

Instead use reqList.addAll(rj.createPublisherRequestObject(string)); which will keep on adding the reult list to the reqList , at end you have all the value.

You need to do reqList.add(rj.createPublisherRequestObject(string)); You were not adding that's why it's returning last iteration value.

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