从数组java中随机删除元素

时间:2016-02-07 13:24:11

标签: java arrays random

我在下面的代码中从数组中删除元素。在这个特定的代码中,我将删除pos 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]);
        }   
    }
}

3 个答案:

答案 0 :(得分:1)

删除此元素:

int randomLocation = new Random().nextInt(countries.length);
// countries[randomLocation]  <--- this is the "random" element.

或者在一行中:

countries[(new Random()).nextInt(countries.length)];

因此,为了实际删除元素,您可以使用ArrayUtils: 首先导入这些

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);

答案 1 :(得分:1)

Random r = new Random();
int result = r.nextInt(size);
//and select/remove countries[result]

这为您提供0到5之间的伪随机数(不包括)。 小心你的size变量,我认为它没有明确定义。

答案 2 :(得分:0)

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

public <E> E removeRandom(List<E> list, Random random) {
    if (list.isEmpty())
        throw new IllegalArgumentException();

    int index = random.nextInt(list.size());
    int lastIndex = list.size() - 1;

    E element = list.get(index);
    list.set(index, list.get(lastIndex));
    list.remove(lastIndex);

    return element;
}