英文:
How do i get this 2*2 matrix by adding array in List
问题
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
List<List<Integer>> list = new List<List<Integer>>();
list.add({1, 2, 3});
list.add({3, 4, 5});
list.add({6, 7, 8});
System.out.println(list);
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
List<List<Integer>> list = new ArrayList<>();
list.add(Arrays.asList(1, 2, 3));
list.add(Arrays.asList(4, 5, 6));
list.add(Arrays.asList(7, 8, 9));
System.out.println(list);
System.out.println(list.get(0).get(0));
}
}
英文:
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
List<List<Integer>> list = new List<List<Integer>>();
list.add({1,2,3});
list.add({3,4,5});
list.add({6,7,8});
System.out.println(list);
}
}
** I want the below matrix. And i want it by adding array to the List, but i amnot getting the desire output. Please let me know what i am missing.
1 2 3
4 5 6
7 8 9
below code is working, and i have updated incase anyone needs....
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
List<List<Integer>> list = new ArrayList<>();
list.add(Arrays.asList(1,2,3));
list.add(Arrays.asList(4,5,6));
list.add(Arrays.asList(7,8,9));
System.out.println(list);
System.out.println(list.get(0).get(0));
}
}
答案1
得分: 2
你不能实例化List,因为它是一个接口,你应该使用其中一个列表实现来创建新的列表,例如ArrayList。
List<List<Integer>> list = new ArrayList<>();
并将元素添加到列表中。
list.add(Arrays.asList(6, 7, 8));
英文:
You cannot instantiate List because its interface you should create new list using one of list implementation e.g. Arraylist
List<List<Integer>> list = new ArrayList>();
and adding to list
list.add(Arrays.asList(6,7,8));
</details>
# 答案2
**得分**: 1
list.forEach(rowList -> {
rowList.forEach(number -> System.out.print(number + " "));
System.out.println();
});
<details>
<summary>英文:</summary>
list.forEach(rowList -> {
rowList.forEach(number -> System.out.print(number + " "));
System.out.println();
});
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论