如何从二维数组列表中获取价值 [英] how to get value from 2d arraylist

查看:65
本文介绍了如何从二维数组列表中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为sub和main的数组列表,

i have arraylists named sub and main,

ArrayList main = new ArrayList();

ArrayList sub=new ArrayList();

我向sub添加值,然后向main添加sub.

i add value to sub and then add sub to main.

示例;

 sub.add(1);
 sub.add(2);
 main.add(sub);

现在我想在sub内获取所有值

now i want to get all values inside sub

 so i used following one but .get(j) gives me the error get >> canot find symbol

for (int i=0;i<main.size();i++) {
       System.out.println();

       for (int j=0;j<sub().size();j++) {
            System.out.print(main.get(i).get(j));//error line
       }
}

如何获取主arraylist的子数组中的所有值

how can i get all values inside subarray of main arraylist

推荐答案

将变量声明为

ArrayList main;

此列表包含Object个.这意味着即使添加ArrayListmain.get(i)也只会返回Object.这就是为什么会出现编译器错误的原因:Object没有名为get()的方法.

This list holds Objects. This means that main.get(i) will only return an Object, even if you add ArrayLists. That's why you get a compiler error: Object doesn't have a method named get().

要解决此问题,您需要使用泛型:

To fix the problem, you need to use generics:

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

ArrayList<Integer> sub=new ArrayList<>();

现在get()将返回具有get()方法的List<Integer>,因此编译器错误将消失.

Now get() will return a List<Integer> which has a get() method, so the compiler error will disappear.

这篇关于如何从二维数组列表中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆