如何通过将列表中的数组相加来获得这个2*2矩阵

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

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(&quot;Hello World&quot;);
		
		List&lt;List&lt;Integer&gt;&gt; list = new List&lt;List&lt;Integer&gt;&gt;();
		
		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(&quot;Hello World&quot;);
		
	    List&lt;List&lt;Integer&gt;&gt; list = new ArrayList&lt;&gt;();
		
		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&lt;List&lt;Integer&gt;&gt; list = new ArrayList&gt;();

and adding to list

list.add(Arrays.asList(6,7,8));



</details>



# 答案2
**得分**: 1

list.forEach(rowList -&gt; {
  rowList.forEach(number -&gt; System.out.print(number + &quot; &quot;));
  System.out.println();
});

<details>
<summary>英文:</summary>

    list.forEach(rowList -&gt; {
      rowList.forEach(number -&gt; System.out.print(number + &quot; &quot;));
      System.out.println();
    });

</details>



huangapple
  • 本文由 发表于 2020年8月5日 20:30:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63265263.html
匿名

发表评论

匿名网友

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

确定