/*
Create List from Java Object Array Example 利用数组创建List的示例
This java example shows how to create a List from an array of type Object using
这个Java示例展示了如何使用Arrays的asList方法来利用一个数组生成List对象
asList method of Arrays class.
*/
import java.util.Arrays
import java.util.List;
import java.util.Iterator;
public class CreateListFromObjectArrayExample{
public static void main(String[] args){
//create an array of type Object, in this case we will create String array、
//创建一个数组类型对象,在这个示例中我们创建一个字符串数组
String[] strArray= new String[]{"Object","Array","Converted","To","List"};
/*
To create List from an array of type Object use,
static List asList(Object[] objArray) method of Arrays class.
This method returns a fixed sized list backed by original array.
为了利用一个数组对象初始化创建List,我们使用 Arrays类中的asList()这个静态方法。
这个方法返回一个与原始数组对象相同长度的List
*/
List list = Arrays.asList(strArray);
//get an iterator 取得一个迭代器
Iterator itr = list.iterator();
//iterate through list created from Array 遍历使用数组生成的list
System.out.println("List created from an Array of type Object contains,");
while(itr.hasNext())
System.out.println(itr.next());
}
}
/*
Output would be 输出为:
List created from an Array of type Object contains,
Object
Array
Converted
To
List
*/
这个实例通过Arrays.asList()方法将一个数组转换成了List,但是需要注意,这个生成的List不是java.util.ArrayList而是Arrays的内部类。所以不能直接在其上执行add()等java.util.ArrayList才有的方法。
参考:http://blog.csdn.net/wanbin021614/article/details/1771384
原文:http://www.java-examples.com/create-list-java-object-array-example