英文:
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.
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
得分: 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<List<Integer>> q = new ArrayList<>();
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<List<Integer>> q = new ArrayList<>();
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 < q.size(); i++) {
for (int j = 0; j < ((List) q.get(i)).size(); j++) {
System.out.print(((List) q.get(i)).get(j)+ " ");
}
}
}
Hope this helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论