You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现从列表随机选取并移除元素直至剩余一个的高效方法

解决方案:动态随机移除列表元素直至剩余一个

你的核心问题在于使用了固定长度的数组,没法动态移除元素,而且每次循环都重新初始化数组,导致元素永远不会减少。改用ArrayList(支持动态增删的集合)就能高效解决这个问题,不用写大量嵌套判断。

修正后的代码

package randomlist;

import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;

public class Output { // 类名首字母大写符合Java规范

    public static void main(String[] args) {
        // 初始化颜色列表,转成ArrayList方便动态移除
        ArrayList<String> colors = new ArrayList<>();
        colors.add("Black");
        colors.add("White");
        colors.add("Red");
        colors.add("Blue");
        colors.add("Green");
        colors.add("Mint");
        colors.add("Rose");
        colors.add("Purple");

        // 循环直到列表只剩1个元素
        while (colors.size() > 1) {
            // 生成0到当前列表长度-1的随机索引
            int randomIndex = ThreadLocalRandom.current().nextInt(colors.size());
            // 取出并移除该索引的元素
            String selectedColor = colors.remove(randomIndex);
            System.out.println(selectedColor);
        }

        // 打印最后剩下的元素
        System.out.println("最后剩余元素:" + colors.get(0));
    }
}

关键说明

  • 用ArrayList替代数组:数组长度固定,无法直接删除元素;ArrayList的remove(int index)方法可以直接移除指定位置的元素,同时自动调整列表长度。
  • 动态生成随机索引:每次循环都基于当前列表的size()生成随机索引,确保不会越界。
  • 循环逻辑:用while循环判断列表大小,直到只剩1个元素停止,无需手动写固定次数的循环。
  • 规范修正:类名首字母大写(Output而非output),移除了没用的Robot相关导入(原代码没用到),让代码更简洁。

内容的提问来源于stack exchange,提问作者Jacob Christonsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 06:14:59