Java 程序将列表转换为数组
List 对象提供一个称为 toArray() 的方法。此方法接受一个空数组作为参数,将当前列表转换为数组并放入给定的数组中。要将 List 对象转换为数组 -
- 创建一个 List 对象。
- 向其添加元素。
- 使用已创建的 ArrayList 的大小创建一个空数组。
- 使用 toArray() 方法 将列表转换为数组,传递上述创建的数组作为参数。
- 打印数组的内容。
示例
import java.util.ArrayList;
public class ListToArray {
public static void main(String args[]){
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Orange");
list.add("Banana");
System.out.println("Contents of list ::"+list);
String[] myArray = new String[list.size()];
list.toArray(myArray);
for(int i=0; i<myArray.length; i++){
System.out.println("Element at the index "+i+" is ::"+myArray[i]);
}
}
}输出
Contents of list ::[Apple, Orange, Banana] Element at the index 0 is ::Apple Element at the index 1 is ::Orange Element at the index 2 is ::Banana
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP