小编Agu*_*Val的帖子

如何从ArrayList中删除随机元素

我有一个 ArrayList,我想随机获取一个元素,删除该元素并在没有删除的元素的情况下进行另一个随机。我怎样才能做到这一点?我曾尝试过,但没有成功。

谢谢。

主要活动:

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;

    ArrayList<Integer> list = new ArrayList<Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.button);
        textView = (TextView)findViewById(R.id.textView);

        list.add(0);
        list.add(1);
        list.add(2);
        list.add(3);

    }

    public void button(View view) {
        Random rand = new Random();
        int randomElement = list.get(rand.nextInt(list.size()));
        if (list.isEmpty()) {
            textView.setText("Empty");
        } else if (randomElement == 0) {
            textView.setText("Red");
            list.remove(randomElement);
        } else if (randomElement == 1) {
            textView.setText("Blue");
            list.remove(randomElement);
        } else if (randomElement == 2) …
Run Code Online (Sandbox Code Playgroud)

java random android arraylist

0
推荐指数
1
解决办法
1816
查看次数

标签 统计

android ×1

arraylist ×1

java ×1

random ×1