Jump to content

Java SE8 nee help with ArrayList !

Go to solution Solved by dronikal,

oh lol found my mistake sorry for the post it appears since the list is empty before the for cycle its size is 0 and so the for cycle does absolutely nothing 

Hello!I'm studying Java SE 8 and i have to  create an ArrayList full of random numbers between 0 and 1000 . PLS help!
P.S I'm new to Java and programming so pls explain. I have this as script for now but i don't get why it won't add the random numbers:

package zadacha;

import java.util.ArrayList;
import java.util.Random;

public class reshenie {

    public static void main(String[] args) {
        ArrayList<Integer> list=new ArrayList<>(); 
        Random gen=new Random();
        for (int i = 0; i <list.size(); i++) {
            int counter=gen.nextInt();
            list.add(counter);
            
        }
        
    }

}
 

Link to comment
https://linustechtips.com/topic/569739-java-se8-nee-help-with-arraylist/
Share on other sites

Link to post
Share on other sites

In your for loop, your termination condition is i<list.size(). However, your list initially has size 0, so it does not add any numbers. You need to start the arraylist with an initial capacity (... new Arraylist<>(number)), or change list.size() to some number.

 

edit: posted at the same time as you, you're correct. 

Link to post
Share on other sites

Change the terminating condition of the for loop to the amount of numbers you want in your list.

Using the list size itself would result in an infinite loop since you are constantly increasing the size of the list with each iteration.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×