方法一:使用Arrays.asList()方法
1
2
String[]asset={"equity","stocks","gold","foreign exchange","fixed income","futures","options"};
ListassetList=Arrays.asList(asset);
对于Arrays.asList()方法需要注意以下几点:
1.该方法返回的是基于数组的List视图(List view)。所以,这种方式是将数组转换为List的最快的方式。因为返回的只是视图,不需要多余的内存来创建新的List以及复制操作。
2.该方法返回的List是长度是固定的(fixed),不是只读的。所以我们不能进行删除、添加操作,而可以使用set()方法进行修改元素操作。如果你对返回的List执行add()添加新元素,会返回UnsupportedOperationException。至于为什么报这个异常,文章末尾我会给出解释。
3.因为该方法返回的是基于原数组的List视图,所以,当我们使用set方法修改了List中的元素的时候,那么原来的数组也会跟着改变(这是视图的特性)。
4.从java 5开始,该方法支持泛型,所以我们可以从数组中得到类型安全ArrayList。
注意:
1.如果我们想让转换为只读的List,可以使用Collections.unmodifiableList()方法来将数组转换为指定List。
2.如果想返回的方法能够进行添加、删除元素操作,则可以使用new ArrayList(Arrays.asList(array)) ,这样就会创建一个对象类型的ArrayList,并将数组的内容拷贝过去。
方法二:使用Collections.addAll()方法
该方法没有第一种方法高效,但是更加灵活。同样也是新建一个ArrayList,将数组的内容复制进去。
1
2
3
4
ListassetList=newArrayList();
String[]asset={"equity","stocks","gold","foriegn exchange","fixed income","futures","options"};
Collections.addAll(assetList,asset);
对于该方法需要了解的:
1. 没有Arrays.asList()快,但是更加灵活。
2.该方法实际上是将数组的内容复制到ArrayList中
3.因为是复制内容到ArrayList中,所以我们对ArrayList进行修改、添加、删除操作都不会影响原来的数组。
4.该方法相当于一个添加操作。该方法并不会覆盖ArrayList中已经存在的元素。如下:
1
2
3
4
5
6
7
String[]fooArray={"one","two","three"};
ListassetList=newArrayList();
Collections.addAll(assetList,fooArray);
Collections.addAll(assetList,fooArray);
System.out.println(assetList);
输出为:
[one,two,three,one,two,three]
方法三:使用集合的addAll()方法
1
2
Arraylist newAssetList=newArraylist();
newAssetList.addAll(Arrays.asList(asset));
方法四:使用Spring框架将数组转换为List
Spring框架中的CollectionUtils提供了几个方法来将数组转换为Arraylist。例如:CollectionUtils.arrayToList()。当然,返回的List是不可修改的,不能add()或remove()元素。
1
2
3
4
5
6
7
8
9
String[]currency={"SGD","USD","INR","GBP","AUD","SGD"};
System.out.println("Size of array: "+currency.length);
ListcurrencyList=CollectionUtils.arrayToList(currency);
//currencyList.add("JPY"); //Exception in thread "main" java.lang.UnsupportedOperationException
//currencyList.remove("GBP");//Exception in thread "main" java.lang.UnsupportedOperationException
System.out.println("Size of List: "+currencyList.size());
System.out.println(currencyList);
============================
java中将ArrayList转换为数组的方法
使用toArray()方法:
1
2
3
4
5
6
7
8
9
10
ListassetTradingList=newArrayList();
assetTradingList.add("Stocks trading");
assetTradingList.add("futures and option trading");
assetTradingList.add("electronic trading");
assetTradingList.add("forex trading");
assetTradingList.add("gold trading");
assetTradingList.add("fixed income bond trading");
String[]assetTradingArray=newString[assetTradingList.size()];
assetTradingList.toArray(assetTradingArray);
==================
附加内容:
A.为何对Arrays.asList()返回的List进行添加、删除操作会报错,而set方法却可以使用?
我们来看下Arrays.asList()方法相关源代码,省略其余的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
...
/**
* Returns a fixed-size list backed by the specified array. (Changes to
* the returned list "write through" to the array.) This method acts
* as bridge between array-based and collection-based APIs, in
* combination with {@link Collection#toArray}. The returned list is
* serializable and implements {@link RandomAccess}.
*
*
This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
*
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
*
*
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/
@SafeVarargs
publicstaticListasList(T...a){
returnnewArrayList<>(a);
}
/**
* @serial include
*/
privatestaticclassArrayListextendsAbstractList
implementsRandomAccess,java.io.Serializable
{
privatestaticfinallongserialVersionUID=-2764017481108945198L;
privatefinalE[]a;
ArrayList(E[]array){
if(array==null)
thrownewNullPointerException();
a=array;
}
publicintsize(){
returna.length;
}
publicObject[]toArray(){
returna.clone();
}
publicT[]toArray(T[]a){
intsize=size();
if(a.length
returnArrays.copyOf(this.a,size,
(Class<?extendsT []>)a.getClass());
System.arraycopy(this.a,0,a,0,size);
if(a.length>size)
a[size]=null;
returna;
}
publicEget(intindex){
returna[index];
}
publicEset(intindex,Eelement){
EoldValue=a[index];
a[index]=element;
returnoldValue;
}
publicintindexOf(Objecto){
if(o==null){
for(inti=0;i
if(a[i]==null)
returni;
}else{
for(inti=0;i
if(o.equals(a[i]))
returni;
}
return-1;
}
publicbooleancontains(Objecto){
returnindexOf(o)!=-1;
}
}
...
解释:
我们注意到Arrays.asList()方法返回的是个内部的ArrayList,这个类同样是AbstractList的一种实现,AbstractList的add和remove方法会有异常抛出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* {@inheritDoc}
*
*
This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
publicvoidadd(intindex,Eelement){
thrownewUnsupportedOperationException();
}
/**
* {@inheritDoc}
*
*
This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
publicEremove(intindex){
thrownewUnsupportedOperationException();
}
,而该ArrayList就只有以下方法,并没有实现add和remove方法:
contain(Object)
get(int)
indexOf(Object)
set(int)
size()
toArray()
toArray(T[])
根本就没有add()和remove()方法,所以 当我们对返回的List执行add和remove方法时,就会报UnsupportedOperationException了。但是因为有set()方法,所以,我们可以修改返回的List。
B.我们说Arrays.asList()返回的是基于原数组的List视图, 而且修改List的元素时候,原数组的内容也会同时改变,这又是为何呢?
解释:根据上面的代码,我们可以知道, 我们调用返回的ArrayList的set(),get(), indexOf(), contain(),size()这些方法,本质上都是去对原数组进行对应的操作。所以,我们改变返回的ArrayList中的内容的时候,原数组也会同时改变。这就是集合视图(collection view),集合了常用的方法。
C.为何返回的ArrayList的长度是固定的?还有为什么Arrays.asList()方法最快?
解释:还是上面的代码,一般来说,ArrayList内部有一个对象类型数组作为实例变量来存放ArrayList中的数据。而上面的内部类中,ArrayList的这个实例变量就是a,而它只是将引用指向了原数组,并未将原数组的内容复制到a中。这样就没有进行复制操作,也没有创建新的数组对象,自然最快了。
同时,该内部类ArrayList并为提供add方法等方法,自然是无法修改ArrayList的长度。而且因为是直接将实例变量a指向原数组,我们知道数组一旦初始化后就没法修改它的大小了,所以原数组不能改变大小,自然返回的ArrayList的长度也不能改变长度,长度就只能是固定的。
参考:《3 Exampls to Convert an Array to ArrayList in Java》
http://javarevisited.blogspot.sg/2011/06/converting-array-to-arraylist-in-java.html
感谢:
N3verL4nd 的建议,增加UnsupportedOperationException来源进一步说明
转载请注明:大步's Blog » 将java中数组转换为ArrayList的方法实例(包括ArrayList转数组)
转载于:https://www..com/GarfieldEr007/p/7082945.html