无法访问嵌套列表的大小或元素。

huangapple go评论100阅读模式
英文:

Not Able to Access size or element of Nested list

问题

我在访问Java中内部列表的大小或元素时遇到错误

[这是我遇到的错误][1]

    public static void main(String... args) {
        List list = new ArrayList();

        List<Integer> list2 = Arrays.asList(1, 2, 3);
        List<Integer> list3 = Arrays.asList(5, 6);
        List<Integer> list4 = Arrays.asList(7, 8, 9);

        list.add(list2);
        list.add(list3);
        list.add(list4);

        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.get(i).size(); j++) {
                System.out.print(list.get(i).get(j) + " ");
            }
        }
    }

  [1]: https://i.stack.imgur.com/MMzH8.png
英文:

I'm getting error while accessing the size or element of inner list in Java.

This is the Error I'm getting

public static void main(String... args) {
    List list = new ArrayList();

    List&lt;Integer&gt; list2 = Arrays.asList(1,2,3);
    List&lt;Integer&gt; list3 = Arrays.asList(5, 6);
    List&lt;Integer&gt; list4 = Arrays.asList(7, 8, 9);

    list.add(list2);
    list.add(list3);
    list.add(list4);

    for (int i = 0; i &lt; list.size(); i++) {
        for (int j = 0; j &lt; list.get(i).size(); j++) {
            System.out.print(list.get(i).get(j)+ &quot; &quot;);
          }
       }
    }
}

答案1

得分: 1

你对列表 q 的声明缺少它所包含的对象类型的信息。

List<List<Integer>> q = new ArrayList<>();

没有这些信息,编译器只能知道它包含某种类型的对象,因此 q.get() 必须具有类型 Object。但在 Object 类中没有 get()size() 方法,这就是你得到的错误。

英文:

Your declaration of the list q is missing the information of what kind of objects it contains.

List&lt;List&lt;Integer&gt;&gt; q = new ArrayList&lt;&gt;();

Without this information, the only thing the compiler can know is that it contains objects of some kind, so q.get() must have type Object. But there are no get() nor size() methods in Object class, and that's the error you get.

答案2

得分: 0

你应该使用List<List<Integer>> q = new ArrayList<>();,而不是List q = new ArrayList();,因为你正在将一组列表插入到q中。

英文:

You should be using List&lt;List&lt;Integer&gt;&gt; q = new ArrayList&lt;&gt;(); instead of List q = new ArrayList(); since you are inserting a group of lists in q.

答案3

得分: 0

以下是您循环代码的更新部分,基本上您需要将 q.get(i) 转换为 List。

for (int i = 0; i < q.size(); i++) {
    for (int j = 0; j < ((List) q.get(i)).size(); j++) {
        System.out.print(((List) q.get(i)).get(j) + " ");
    }
}

希望这能有所帮助。

英文:

Update you loop code with following, basically you need to cast the q.get(i) into List.

 for (int i = 0; i &lt; q.size(); i++) {
        for (int j = 0; j &lt; ((List) q.get(i)).size(); j++) {
            System.out.print(((List) q.get(i)).get(j)+ &quot; &quot;);
          }
       }
    }

Hope this helps.

huangapple
  • 本文由 发表于 2020年4月8日 03:37:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/61088078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定