cat000
cat000

Reputation: 35

How to create a method that generates an arraylist of random number

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

public static void main(String[] args) {
    ArrayList<Integer> random = new ArrayList<Integer>();
    random = getRandom(100, 100);
    for (int i = 0; i < random.size(); i++)
        System.out.println(random.get(i));
}

private static ArrayList<Integer> getRandom(int range, int size) {
    ArrayList<Integer> randomNumbers = new ArrayList<Integer>();
    for (int i = 0; i < size; i++)
        randomNumbers.set(i, new Random().nextInt(range)+1);
    return randomNumbers;
}

Whenever I run this, I get an Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

Upvotes: 2

Views: 1644

Answers (5)

uzilan
uzilan

Reputation: 2624

If you want, you could also use the functional style:

List<Integer> list = IntStream.range(0, 100)
    .mapToObj(i -> random.nextInt(100))
    .collect(Collectors.toList());

This will minimize the moving parts that are part of what's causing your problem :)

Upvotes: 0

Mohit Gupta
Mohit Gupta

Reputation: 5

arrayList.set(index, value) method is used to replace old value with new value. But in your case, you are not replacing a value. You are just simply adding values.
So, Use add method of list.



randomNumbers.add(new Random().nextInt(range)+1);

And for printing the values of Arraylist, you are using:

for (int i = 0; i < random.size(); i++)
        System.out.println(random.get(i));

but no need to iterate it through for loop, You can directly print this like below:

System.out.println(random);

Upvotes: 0

Mike
Mike

Reputation: 542

In addition to JDev's correct response above, take a look at the description of ArrayList#set's Javadoc:

Replaces the element at the specified position in this list with the specified element.

So, the specified index has to already be populated in order for the ArrayList#set call to succeed.

Upvotes: 0

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17142

Change

randomNumbers.set(i, new Random().nextInt(range)+1);

to

randomNumbers.add(new Random().nextInt(range)+1);

the set() method of an ArrayList works an EXISTING element of the ArrayList, but in your case it's empty, which means that the first call to

randomNumbers.set(i, new Random().nextInt(range)+1);

where i == 0 is invalid. Use add() instead.

Upvotes: 3

Sajan Chandran
Sajan Chandran

Reputation: 11487

Arraylist are backed by arrays, when you use set method with an index, it tries to set the value at the index since the backed array is empty you get an IndexOutOfBoundsException, so first you need to populate the Arraylist.

For that you need to use the add method, instead of set

Upvotes: 0

Related Questions