繁体   English   中英

将List转换为Array之间的区别

[英]Difference between converting List to Array

我只是想知道以下两种将List转换为Array的方法有什么区别。

List<String> test = new ArrayList<String>();
test.add("AB");
test.add("BC");
test.add("CD");
test.add("DE");
test.add("EF");

String[] testarray = test.toArray(new String[0]); // passing 0 as Array size

低于一:

List<String> test = new ArrayList<String>();
test.add("AB");
test.add("BC");
test.add("CD");
test.add("DE");
test.add("EF");

String[] testarray = test.toArray(new String[test.size()]); // passing list's size

我在控制台上获得了相同的testarray输出。

public <T> T[] toArray(T[] a)

a - 如果列表元素足够大,这是要存储列表元素的数组; 否则,为此目的分配相同运行时类型的新数组。 因此,在第一种情况下,正在创建一个新数组,而在第二种情况下,它使用相同的数组。

示例代码:

情况-1:传递的数组可以包含列表元素

public static void main(String[] args) {
        List<String> test = new ArrayList<String>();
        test.add("AB");
        test.add("BC");
        test.add("CD");
        test.add("DE");
        test.add("EF");
        String[] s= new String[10];
        String[] testarray = test.toArray(s); 
        System.out.println(s==testarray);
    }

O/P :

true

情况2:传递的数组不能保存列表元素

public static void main(String[] args) {
        List<String> test = new ArrayList<String>();
        test.add("AB");
        test.add("BC");
        test.add("CD");
        test.add("DE");
        test.add("EF");
        String[] s= new String[0];
        String[] testarray = test.toArray(s); 
        System.out.println(s==testarray);

    }

O/P :

false

暂无
暂无

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

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