Remove random item from ArrayList

2019-07-11 06:14发布

I'm new to android. I have an ArrayList of strings and that ArrayList contain questions that are selected randomly and set in a TextView. when the user click next it Should be go to the next activity for another question which is also selected from the ArrayList. I want to remove the first question from the Arraylist to prevent duplication in the second activity. How can I do that?

here is how I did it:

int rando = (int)((Math.random()*10));

textView.setText(myArrayList.get(rando));

I'm using Intent to pass myArrayList to the second activity.

but I can't figure out how to remove the item in the textView before going the next activity. I used myArrayList.remove(textView.getText()); but not working.

3条回答
Animai°情兽
2楼-- · 2019-07-11 06:21

Try using myList.remove(rando);, where rando is index

public static void main(String[] args) {
        List<String> myList = new ArrayList<String>();
        myList.add("abc1");
        myList.add("abc2");
        myList.add("abc3");
        myList.add("abc4");

        int rando = (int) ((Math.random() * myList.size()));
        System.out.println(rando);
        String text = myList.get(rando);
        System.out.println(text);
        System.out.println(myList);

        myList.remove(rando);
        System.out.println(myList);

    }

output

2
abc3
[abc1, abc2, abc3, abc4]
[abc1, abc2, abc4]
查看更多
在下西门庆
3楼-- · 2019-07-11 06:25

First, keep the rando value. then use it when you're starting the next activity like this:

myArrayList.remove(rando);
查看更多
孤傲高冷的网名
4楼-- · 2019-07-11 06:44

You can try to remove item by it's position.

instead of this,

myArrayList.remove(textView.getText());

you have to use below code

myArrayList.remove(rando);
查看更多
登录 后发表回答