嗨,我正在编写一个java程序,其中我需要随机读取添加到Vector中的对象,并且不应该重复。实际上我想通过 Math.random() * Vector.size() 获得一个随机数并且不重复,将随机数保留在数组或其他东西中以便下次不再读取它但猜测必须有一个方法或为此目的的东西...... 我将感谢您的任何回复
最佳答案
您可以生成一个从 1
直到 vector 大小的序列,对其进行打乱,然后使用这些值从 vector 中读取元素:
Vector v;
List<Integer> values = new ArrayList<>();
for (int i=0; i < v.size(); ++i) {
values.add(i);
}
Collections.shuffle(values);
// now read the value in the vector using this random sequence
for (int i=0; i < values.size(); ++i) {
System.out.println(vector.get(values.get(i)));
}
关于java - 从 Vector java 读取随机对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43188981/