从java数组中随机删除元素

从java数组中随机删除元素,java,arrays,random,Java,Arrays,Random,在下面的代码中,我正在从数组中删除元素。在这个特殊的代码中,我正在移除位置2处的元素。如何删除此数组中的随机元素 public class QuestionOneA2 { public static void main(String[] args) { int size = 5; int pos = 2; String[] countries = {"Brazil", "France", "Germany", "Canada", "Italy", "England"}

在下面的代码中,我正在从数组中删除元素。在这个特殊的代码中,我正在移除位置2处的元素。如何删除此数组中的随机元素

public class QuestionOneA2 {

public static void main(String[] args) {
    int size = 5;
    int pos = 2;

    String[] countries = {"Brazil", "France", "Germany", "Canada", "Italy", "England"};

        for (int i = 0; i < size; i++) {
            if(i == pos) {
                countries[i] = countries[size];
            }
            System.out.println(countries[i]);
        }   
    }
}
公开课问题A2{
公共静态void main(字符串[]args){
int size=5;
int pos=2;
字符串[]国家={“巴西”、“法国”、“德国”、“加拿大”、“意大利”、“英国”};
对于(int i=0;i
删除此元素:

int randomLocation = new Random().nextInt(countries.length);
// countries[randomLocation]  <--- this is the "random" element.
因此,为了实际移除该元素,您可以使用: 先进口这些

import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;
然后:

countries = ArrayUtils.removeElement(countries, countries[(new Random()).nextInt(countries.length)]);
如果您真的不想使用
ArrayUtils
,那么您可以使用:

List<String> list = new ArrayList<String>(Arrays.asList(countries));
list.removeAll(Arrays.asList(countries[(new Random()).nextInt(countries.length)]));
countries = list.toArray(countries);
List List=newarraylist(Arrays.asList(countries));
list.removeAll(Arrays.asList(countries[(new Random()).nextInt(countries.length)]);
国家=列表。toArray(国家);
这将为您提供一个介于0和5之间的伪随机数(独占)。
小心使用
大小
变量,我认为它没有很好地定义。

如果您不介意元素的顺序,也可以在恒定时间内实现此行为:

public E-removeRandom(列表,随机){
if(list.isEmpty())
抛出新的IllegalArgumentException();
int index=random.nextInt(list.size());
int lastIndex=list.size()-1;
E元素=list.get(索引);
set(index,list.get(lastIndex));
删除(lastIndex);
返回元素;
}

使用例如
int size=countries.length-1
或仅
countries.length-1
而不是固定大小;否则你就做错了。如果我这样做,我应该在for循环中放什么?@StudentCoder我用更清晰的命令编辑了我的答案(删除你的
for
循环)谢谢,我实际上是想用for循环来解决这个问题,虽然在这个程序中,
for
循环是没有用的,这是浪费空间和时间的。这是我试图做的两部分问题的第一部分,这将要求用户输入缺少的国家,我被指示使用for循环,我是不是完全错误地看待他?
List<String> list = new ArrayList<String>(Arrays.asList(countries));
list.removeAll(Arrays.asList(countries[(new Random()).nextInt(countries.length)]));
countries = list.toArray(countries);
Random r = new Random();
int result = r.nextInt(size);
//and select/remove countries[result]