将List转换为Array之间的区别

Vim*_*era 4 java arrays collections list

我只是想知道以下两种将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
Run Code Online (Sandbox Code Playgroud)

低于一:

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
Run Code Online (Sandbox Code Playgroud)

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

Oun*_*ney 11

public <T> T[] toArray(T[] a)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

情况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
Run Code Online (Sandbox Code Playgroud)

  • @TheLostMind - 现在,从代码片段中可以清楚地看到...... !! 谢谢 (2认同)
  • 额外的1改善我的答案:) (2认同)