java - 为什么需要 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;
如果不是,为什么会这样?
解决方案
这是为了类型安全。在调用 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);
}
推荐阅读
- docusignapi - 嵌入式发送和发起者需要签名
- arrays - 无法解析 Perl 数组中的标量
- php - Livewire - 嵌套组件 - 内联 javascript 不起作用
- python - 如何使层顺序的输入0兼容?
- java - Java 11 HttpClient 错误的字符编码
- android - 颤振相同尺寸值的小部件在Android和IOS上具有不同的实际尺寸
- sql-server - SQL Server:设置所有权限
- node.js - 使用 Prometheus 对池进行 Sequelize 监控
- python - 如何在python中检查AWS S3中是否已经存在存储桶
- ios - 如何自动连接 CBPeripheral(带有 iBeacon + 蓝牙芯片的 BLE 设备)并且应用程序未运行