首页 > 解决方案 > 为什么需要 LinkedList 的 toArray(T[] a) 方法中的变量“结果”?

问题描述

我目前正在尝试了解 JDK 中 LinkedList 的实现,我在方法中偶然发现了以下内容

toArray(T[] a)

所以在第 1101 行我不知道为什么要result创建变量。由于 LinkedList 和 Array 中的项目是的,T我们不能在下面的 for 循环中做到这一点result吗?

for (Node<E> x = first; x != null; x = x.next)
    a[i++] = x.item;

如果不是,为什么会这样?

标签: javaarrayslinked-list

解决方案


这是为了类型安全。在调用 toArray 之前创建数组时,您可以控制数组的类型。如果让 toArray 创建结果,则它始终是 Object 数组。

这应该说明如何使用 toArray:

public void example ()
{
    List<String> data = new ArrayList<> ();
    data.add ("alpha");
    data.add ("beta");
    data.add ("gamma");
    Object[] arrayObjectData = data.toArray ();

    // Elements of the array have type "Object"
    Object o = arrayObjectData[0];
    System.out.printf ("Object from array: %s %n", o);

    String[] arrayStringData = new String[data.size ()];
    data.toArray (arrayStringData);

    // Elements of the array have type "String"
    String s = arrayStringData[0];
    System.out.printf ("String from array: %s %n", s);
}

您必须确保 List 的内容与数组的类型兼容。这将引发异常:

public void badExample ()
{
    // List of Object
    List<Object> data = new ArrayList<> ();
    data.add ("alpha");
    data.add ("beta");
    data.add ("gamma");
    // Object that can't be stored in an array of String
    data.add (Boolean.TRUE);
    Object[] arrayObjectData = data.toArray ();

    // Elements of the array have type "Object"
    Object o = arrayObjectData[0];
    System.out.printf ("Object from array: %s %n", o);

    String[] arrayStringData = new String[data.size ()];
    data.toArray (arrayStringData);

    // Elements of the array have type "String"
    String s = arrayStringData[0];
    System.out.printf ("String from array: %s %n", s);
}

推荐阅读