【问题标题】:Remove random item from ArrayList从 ArrayList 中删除随机项
【发布时间】:2015-11-24 06:00:06
【问题描述】:

我是安卓新手。我有一个字符串数组列表,该数组列表包含随机选择并在 TextView 中设置的问题。当用户单击下一步时,它应该转到另一个问题的下一个活动,该问题也是从 ArrayList 中选择的。我想从 Arraylist 中删除第一个问题,以防止在第二个活动中重复。我怎样才能做到这一点?

我是这样做的:

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

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

我正在使用 Intent 将 myArrayList 传递给第二个活动。

但我不知道如何在进行下一个活动之前删除 textView 中的项目。我用了 myArrayList.remove(textView.getText());但不工作。

【问题讨论】:

    标签: java android android-intent arraylist


    【解决方案1】:

    尝试使用myList.remove(rando);,其中rando 是索引

    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);
    
        }
    

    输出

    2
    abc3
    [abc1, abc2, abc3, abc4]
    [abc1, abc2, abc4]
    

    【讨论】:

      【解决方案2】:

      首先,保持随机值。然后在你开始下一个活动时使用它:

      myArrayList.remove(rando);
      

      【讨论】:

        【解决方案3】:

        您可以尝试按位置删除项目。

        而不是这个,

        myArrayList.remove(textView.getText());
        

        你必须使用下面的代码

        myArrayList.remove(rando);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-19
          • 1970-01-01
          • 1970-01-01
          • 2015-04-14
          • 2016-12-12
          • 2011-06-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多