我有一个 ArrayList,我想随机获取一个元素,删除该元素并在没有删除的元素的情况下进行另一个随机。我怎样才能做到这一点?我已经尝试过,但没有成功。
谢谢。
主要 Activity :
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) {
textView.setText("Yellow");
list.remove(randomElement);
} else if (randomElement == 3) {
textView.setText("Green");
list.remove(randomElement);
}
}
}
最佳答案
我知道您想要做什么,但我建议采用不同的方法 - 将颜色放入列表中。
public enum Colors {
GREEN, RED, YELLOW;
}
...
List<Colors> list = new ArrayList<Colors>(Arrays.asList(Colors.values()));
Random rand = new Random();
...
public void button(View view) {
if (list.isEmpty()) {
textView.setText("Empty");
} else {
Colors randomElement = list.remove(rand.nextInt(list.size()));
textView.setText(randomElement.name());
}
}
关于java - 如何从ArrayList中删除随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48691091/