Java程序将列表转换为数组
List对象提供了一种称为的方法toArray()。此方法接受一个空数组作为参数,将当前列表转换为数组并将其放置在给定数组中。要将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
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短