我有一个 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)