【问题标题】:How to remove an item from a List<Integer> that is inside an array?如何从数组内的 List<Integer> 中删除项目?
【发布时间】:2014-01-11 07:11:01
【问题描述】:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView t;
    List<Integer> listA = Arrays.asList(0,1,2,3);
    List<Integer> listB = Arrays.asList(0,2,4,6,8);
    List<Integer>[] listC = (List<Integer>[])new List[2];

    t = (TextView)findViewById(R.id.textView1);
    listC[0] = listA;
    listC[1] = listB;
    t.setText("Result: "+ listC[0].get(1)); //Result: 1
    listC[0].remove(0); //i get an error in this line
}

我很困惑为什么我没有收到错误:listC[0].get(1) 但有些问题:listC[0].remove(0); 我的代码有问题吗?有没有更有效的方法?请帮我!非常感谢!

【问题讨论】:

  • 你遇到异常还是错误?
  • 请分享堆栈跟踪
  • FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start Activity 这出现在 logcat 中
  • 你在这行做什么 - List[] listC = (List[])new List[2]; ?
  • 对不起,我是安卓新手。我如何共享堆栈跟踪?我在哪里可以找到它?

标签: java android arrays list


【解决方案1】:

您可能会得到UnSupportedOperationException,因为Arrays.asList() 正在重新调整不可修改的列表。所以改变

List<Integer> listA = Arrays.asList(0,1,2,3);
List<Integer> listB = Arrays.asList(0,2,4,6,8);

List<Integer> listA = new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3));
List<Integer> listB = new ArrayList<Integer>(Arrays.asList(0, 2, 4, 6, 8));

【讨论】:

  • 不能修改Arrays.asList方法返回的列表吗?
  • @Octopus Arrays.asList() 返回一个固定大小列表。您不能添加或删除元素
【解决方案2】:

来自 Arrays.asList 的文档:

列出 java.util.Arrays.asList(Integer...array)

public static List asList(T...数组) 在 API 级别 1 中添加 返回指定数组中对象的列表。 List 的大小不能修改,即不支持添加和删除,但可以设置元素。设置元素会修改底层数组。

参数 排列数组。

返回 指定数组的元素列表。

列表的大小不能改变,最好改变

List<Integer> listA = Arrays.asList(0, 1, 2, 3);
List<Integer> listB = Arrays.asList(0, 2, 4, 6, 8);

ArrayList<Integer> listA = new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3));
ArrayList<Integer> listB = new ArrayList<Integer>(Arrays.asList(0, 2, 4, 6, 8));

【讨论】:

    【解决方案3】:

    我建议使用而不是数组 List&lt;List&lt;Integer&gt;&gt; listC = new ArrayList&lt;List&lt;Integer&gt;&gt;(2); 一种更清洁的方式。

    您可以按如下方式进行所有操作。

     public static void main(String args[]) throws Exception {
            List<Integer> listA = Arrays.asList(0, 1, 2, 3);
            List<Integer> listB = Arrays.asList(0, 2, 4, 6, 8);
            List<List<Integer>> listC = new ArrayList<List<Integer>>(2);
            listC.add(listA);
            listC.add(listB);
            System.out.println("Complete List : " + listC);
            System.out.println("First Element :" + listC.get(0));
            listC.remove(1);// removed 2nd element
            System.out.println("List After Removal : " + listC);
        }
    

    输出:

    Complete List : [[0, 1, 2, 3], [0, 2, 4, 6, 8]]
    First Element :[0, 1, 2, 3]
    List After Removal : [[0, 1, 2, 3]]
    

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 2017-12-29
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      相关资源
      最近更新 更多