简体   繁体   English

List 和 List 有什么区别<Integer[]>并列出<List<Integer> &gt; 在 Java 中

[英]What is the difference between List<Integer[]> and List<List<Integer>> in java

What is the difference between List<Integer[]> and List<List> in java. java中 List<Integer[]> 和 List<List> 有什么区别? Are both types of ArrayList? ArrayList 都是两种类型吗? If they are different how to convert to each other.如果它们不同,如​​何相互转换。 Thanks.谢谢。

public static List<Integer[]> fourNumberSum(int[] candidates, int target)  {
    List<List<Integer>> res = new ArrayList<>()
    dfs(candidates, target, res, new ArrayList<Integer>(), 0);
    return res;
}

./Program.java:11: error: incompatible types: List<List<Integer>> cannot be converted to List<Integer[]>
    return res;
           ^

List<Integer[]>

This will create an array of type Integer inside your List .Which means you will have a List which contains it's elements of type Integer[].这将在您的 List 中创建一个 Integer 类型的数组。这意味着您将拥有一个 List,其中包含它的 Integer[] 类型的元素。 But again the array size will be constant.So always you need to know the length of the data items which you are placing inside the Array.So all your List elements(Which are arrays)should have constant size.但是再次数组大小将是恒定的。所以你总是需要知道你放置在数组中的数据项的长度。所以你所有的 List 元素(即数组)应该具有恒定的大小。

List<Integer[]> sampleList = new ArrayList<>();

//Add array elements to list

Integer[] element1 = {15, 20, 40};//Here you need to know the size 
sampleList.add(element1);

//Retrieving the elements from the list 

Integer[] listElement1 = sampleList.get(0);

List<List<Integer>>

This will create a List inside a List .Not an array like before so you can place any amount of data to that particular list.So in this case you don't need to know about the size of data elements which you are going to store like before.这将在 List 内创建一个 List 。不是像以前那样的数组,因此您可以将任意数量的数据放置到该特定列表中。因此在这种情况下,您不需要知道要存储的数据元素的大小就像之前一样。

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

//Add list elements to list

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

element1.add(1);//You can set any number of elements

sampleList.add(element1);

//Retrieving the elements from the list 

List<Integer> listElement1 = sampleList.get(0);

它们不是Integer[]表示整数数组而List<Integer>表示列表,如果要将数组转换为列表,可以执行Arrays.asList(array)

I hope this example will help you understand我希望这个例子能帮助你理解

    List<Integer[]> x = new ArrayList<Integer[]>();
    Integer[] arr1 = new Integer[3];
    arr1[0] = 34;
    arr1[1] = 55;
    arr1[2] = 2;
    Integer[] arr2 = new Integer[3];
    arr2[0] = 34;
    arr2[1] = 55;
    arr2[2] = 2;         
    x.add(arr1);
    x.add(arr2);

    List<List<Integer>> a = new ArrayList<List<Integer>>();        
    List<Integer> y = new ArrayList<Integer>();
    y.add(1);
    y.add(2);
    List<Integer> z = new ArrayList<Integer>();
    z.add(1);
    z.add(2);
    a.add(y);
    a.add(z);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM