Select 打印 ArrayList 中的随机元素然后删除它

Select Random element from ArrayList print then remove It

        ArrayList<String> question = new ArrayList<String>();

        Scanner scan = new Scanner(System.in);
            for (int i=0;i<userQuestionList.size();i++){ //get questions
                if (i%2 == 0){
                    question.add(userQuestionList.get(i));
                }
            }

            for (int j = 0; j < question.size(); j++) { // get ans
                Random ran = new Random();
                System.out.print(question.remove((ran.nextInt(question.size()+1)))+" ");
                String ans = scan.nextLine();
                answer.add(ans);
            }
    }

你好,我有这个问题数组列表,我想随机选择它,然后一个一个地删除它,直到没有更多,这样它就不会加载同一个问题两次,但有一些问题 例如,我在问题数组列表中有 3 个问题,有时它只加载 1 个或两个甚至相同的问题,然后让我出界有人可以帮忙吗?

这是一个糟糕的例子:

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");

Random rand = new Random();

System.out.println("Original list: " + list);

int r = rand.nextInt(list.size());

System.out.println(list.get(r));

list.remove(r);

System.out.println("New list: " + list);

Console:
Original list: [a, b, c, d, e]
e
New list: [a, b, c, d]

快速简单,利用Collections.shuffle

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

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");

        while (!list.isEmpty()) {
            // You don't need to do this on each iteration
            // but this is going to give you a really
            // random result
            Collections.shuffle(list);
            String value = list.remove(0);
            System.out.println(value);
        }
    }
}

首先运行...

e
a
c
d
b

第二个运行...

a
e
d
b
c

显然,每个运行都会给出不同的结果