Shuffle range with arraylist

I am studying Java ArrayList, and I want to fill an ArrayList of 20 Integer(s) with random numbers from 0 to 10. This is my code so far:

import java.util.ArrayList;
import java.util.Collections;

public class manejoListas {
    ArrayList<Integer> lista=new ArrayList<>(20);

    public void llenarLista() {
        for (int i=0; i<20;i++) {
                lista.add(i);
        }
        Collections.shuffle(lista);
        System.out.println(lista);
    }
}

and this is the output:

[3, 5, 9, 10, 19, 8, 6, 4, 15, 2, 0, 18, 16, 12, 14, 7, 17, 13, 1, 11]

How can I get the range from 0 - 10?

Upvotes: 2

Views: 84

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 121998

Java and i want to fill an ArrayList of 20 elements with random numbers from 0 to 10

In that case you need Random numbers. Not shuffle function.

Random rn = new Random();

And then

 for (int i = 0; i < 20; i++) {
        lista.add(rn.nextInt(10););
    }

That keeps adding random numbers between 0 and 10.

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201447

You could change

lista.add(i);

to

lista.add(i / 2);

which will reduce the range to 0 (inclusive) - 10 (exclusive). Note that every number will appear twice. If you want the values to be more randomly distributed, you could use Random.nextInt(int) like

static Random rand = new Random();

public void llenarLista() {
    for (int i = 0; i < 20; i++) {
        lista.add(rand.nextInt(10));
    }
    // Collections.shuffle(lista);
    System.out.println(lista);
}

Upvotes: 2

Related Questions