ArrayList, Loop and requisite if can not work that i want – Java 11

If I understand correctly your question, you’re trying to build a list of 5 integers, in a random order.

A simple way to get there is to generate a list of ordered numbers and then randomly swap them.

First create your list of ordered numbers.

public List<Integer> createOrderedList(int size) {
    List<Integer> list = new ArrayList<>();

    for (int i = 0; i < size; i++) {

    return list;

Then create a method that swaps two elements in the list, given their indexes.

public void swap(List<Integer> list, int i, int j) {
    Integer hold = list.get(i);
    list.set(i, list.get(j));
    list.set(j, hold);

Last, create a method that mixes all of them.

public void mix(List<Integer> list) {
    Random random = new Random();

    for (int i = 0; i < list.size(); i++) {
        swap(list, i, random.nextInt(list.size()));

Call the methods in this order:

List<Integer> list = createOrderedList(5);

for (int i = 0; i < list.size(); i++) {

Browse More Popular Posts

Leave a Comment