有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何访问ArrayList元素列表

我有ArrayList元素的列表,请参见下面

List<List<String>> x = new ArrayList<List<String>>();

它包含一些数组列表元素

例如

x.get(0)->[1,2,3,4],
x.get(1)->([5,6,7,8],
x.get(2)->[9,10,11,12],
x.get(3)->[13,14,15,16]

我想从x.get(0)访问元素3,或从x.get(1)访问元素7。如何调用


共 (3) 个答案

  1. # 1 楼答案

    你可以像…一样跟随

    List<List<String>> x = new ArrayList<List<String>>();
    List<String> subX = x.get(7);
    if(null != subX && subX.size() != 0) {
        String element = subX.get(0);
    }
    
  2. # 2 楼答案

    列表中的每个元素都是一个列表,具有提供List<T>方法的相同接口,例如

    • T get(int index)
    • boolean isEmpty()
    • void add(T element)
    • 等等

    您可以通过索引从内部列表访问元素

    List<List<String>> x = new ArrayList<List<String>>();
    // ... some data initialised
    String element_0_3 = x.get(0).get(3);
    

    请注意,在访问每个List<String>元素之前,需要先创建它。例如,要在[0,0]坐标处添加新的String,请执行以下操作:

    List<List<String>> x = new ArrayList<List<String>>();
    List<String> x0 = new ArrayList<>();
    x0.add("foo"); // add "foo" as the first string element
    x.add(x0); // add x0 as the first List<String> element
    

    您还可以使用增强的for循环读取值,而无需使用索引:

    List<List<String>> x = new ArrayList<List<String>>();
    //...
    for (List<String> ls : x) { // iteration on the x list
       for (String s : ls) {    // iteration on each intern list
          System.out.println(s);
    } 
    
  3. # 3 楼答案

    //使用for循环而不是foreach循环直接访问任何列表成员

    List<List<Integer>> list = new ArrayList<List<Integer>>();
    for(int i=0;i<list.size();i++){
       for(int j=0;j<list.get(i).size();j++){
          do_something_on(list.get(i).get(j);
       }
    }