[英]how to get value from 2d arraylist
i have arraylists named sub and main, 我有名为sub和main的arraylist,
ArrayList main = new ArrayList();
ArrayList sub=new ArrayList();
i add value to sub and then add sub to main. 我将值添加到sub,然后将sub添加到main。
example; 例;
sub.add(1);
sub.add(2);
main.add(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
}
}
how can i get all values inside subarray of main arraylist 我如何获取主arraylist的子数组内的所有值
When you declare a variable as 当您将变量声明为
ArrayList main;
This list holds Object
s. 此列表包含
Object
。 This means that main.get(i)
will only return an Object
, even if you add ArrayList
s. 这意味着即使您添加
ArrayList
, main.get(i)
也只会返回一个Object
。 That's why you get a compiler error: Object
doesn't have a method named get()
. 这就是为什么会出现编译器错误的原因:
Object
没有名为get()
的方法。
To fix the problem, you need to use generics: 要解决此问题,您需要使用泛型:
ArrayList<List<Integer>> main = new ArrayList<>();
ArrayList<Integer> sub=new ArrayList<>();
Now get()
will return a List<Integer>
which has a get()
method, so the compiler error will disappear. 现在,
get()
将返回具有get()
方法的List<Integer>
,因此编译器错误将消失。
Generics could be your friend here: 泛型可能是您在这里的朋友:
ArrayList<ArrayList<Object>> main = new ArrayList<ArrayList<Object>>(); // or new ArrayList<>(); in Java 7+
ArrayList<Object> sub = new ArrayList<Object>(); // or new ArrayList<>();
If you can't or don't want to use generics, the solution is to cast the expression main.get(i)
to an ArrayList
first: 如果您不能使用泛型,则解决方案是
main.get(i)
表达式main.get(i)
转换为ArrayList
:
System.out.println(((ArrayList) main.get(i)).get(j));
Go through the following code 通过以下代码
public class ArrayListDemo {
public static void main(String[] args) {
List<List<Integer>> main = new ArrayList<>();
List<Integer> sub = new ArrayList<>();
sub.add(1);
sub.add(2);
main.add(sub);
//If you want to get values in sub array list
for(int i = 0; i < 1; i++){
List<Integer> arr = main.get(i);
for(Integer val : arr) System.out.println(val + "");
}
//If you want to print all values
for(List<Integer> list : main){
for(Integer val : list) System.out.println(val + "");
}
}
} }
In the above code, I had declared an ArrayList (main) to keep all Array which are having Integer values. 在上面的代码中,我声明了一个ArrayList(主要)以保留所有具有Integer值的Array。 Also i had declared an another ArrayList (sub) to keep all Integer values.
我也声明了另一个ArrayList(子)来保留所有Integer值。 I had used ArrayList data structure because of length of the List will be changing the run time.
我曾经使用ArrayList数据结构,因为List的长度会改变运行时间。
Good Luck !!! 祝好运 !!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.