【发布时间】:2018-07-19 08:29:32
【问题描述】:
我有一个 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) {
textView.setText("Yellow");
list.remove(randomElement);
} else if (randomElement == 3) {
textView.setText("Green");
list.remove(randomElement);
}
}
}
【问题讨论】:
-
很难理解你的问题是什么?
-
使用
listIterator
标签: java android arraylist random