1

I have a for loop which execute 1000 times ! and I want to save the result of each iteration into an arraylist but it does not save the data from the last iteration ! it just clear the whole arraylist in every iteration and add new items to that !

how should I save the whole data ? I would not add any code because it's really complicated and really hard to explain what's going on in the loop . I want to generally know how to solve the problem and be able to save the whole data

8
  • 1
    Make sure you're not creating a new list every iteration! Learn how to create a minimal usecase that demonstrates the behavior! We can't really address the problem without knowing what your code does! Commented Jun 12, 2012 at 12:43
  • You're going to need to include an extract of your code at least. It's going to be like playing Pin the Tail on the Donkey in the Mariana Trench with a squid attached to your face otherwise. Commented Jun 12, 2012 at 12:43
  • Your question is very unclear, if it is as simple as it sounds, then just inititalize the array outside the loop and keep adding to it! i dont see the big deal here! Post the code, and help us help you! Commented Jun 12, 2012 at 12:44
  • actually the code is in processing.js which use java language and I need someone who knows that! Commented Jun 12, 2012 at 12:47
  • Doesn't matter! We can't just keep guessing! We have no idea what you're doing! What you're doing in the loop is irrelevant, what matters is how/where you create the list, and how you're adding data to it. Commented Jun 12, 2012 at 12:49

3 Answers 3

2

Declare your ArrayList outside of your for loop.

Like so

ArrayList results = new ArrayList();

for (int i = 0; i < 10000; ++i){
    int result = myFunction(i);
    results.add(result);
}
Sign up to request clarification or add additional context in comments.

Comments

2

I would need your code to understand more precisely where does the problem come from but I think it may be because you create a new ArrayList within the loop.

Your code should look like this :

List list = new ArrayList();
for(int i = 0; i < 1000; i++) {
    data = ...
    list.add(data);
}

Comments

0

Create a Empty ArrayList object out side the for loop.get your object in for loop and add it to list.

List<YourClass> list=new ArrayList<YourClass>();

    for(int i=0;i <1000;i++)
    {
        obj=new YourClass();
        list.add(obj);
    }

1 Comment

How does this add useful information not already contained in the two existing answers?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.