java将LinkedList转换为数组,javalinkedlist,下面代码演示如何将Lin
分享于 点击 26701 次 点评:143
java将LinkedList转换为数组,javalinkedlist,下面代码演示如何将Lin
下面代码演示如何将LinkedList转换为数组:
转换使用了List接口的toArray方法,toArray方法接受一个数组的定义作为参数。
package cn.outofmemory.examples;import java.util.LinkedList;import java.util.List;/** * * @author cn.outofmemory */public class Main { public void convertLinkedListToArray() { List<String> theList = new LinkedList<String>(); theList.add("Apples"); theList.add("Bananas"); theList.add("Oranges"); theList.add("Grapes"); String[] fruits = theList.toArray(new String[0]); for (int i = 0; i < fruits.length; i++) { System.out.println(fruits[i]); } } public static void main(String[] args) { new Main().convertLinkedListToArray(); }
我们也可以使用下面的方法来转换:
String[] fruits = new String[theList.size()]; theList.toArray(fruits);
输出结果如下:
ApplesBananasOrangesGrapes
用户点评