方法一:使用Arrays.asList()方法
1
2
|
String[] asset = {"equity", "stocks", "gold", "foreign exchange","fixed income", "futures", "options"};
List<String> assetList = 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
|
List<String> assetList = new ArrayList();
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"};
List<String> assetList = new ArrayList();
Collections.addAll(assetList,fooArray);
Collections.addAll(assetList,fooArray);
System.out.println( assetList);
輸出為:
[one, two, three, one, two, three]
|
方法三:使用集合的addAll()方法
1
2
|
Arraylist newAssetList = new Arraylist();
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);
List<String> currencyList = 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
|
List<String > assetTradingList = new ArrayList();
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 = new String[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}.
*
* <p>This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
* <pre>
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
* </pre>
*
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
/**
* @serial include
*/
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
public int size() {
return a.length;
}
public Object[] toArray() {
return a.clone();
}
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size)
return Arrays.copyOf(this.a, size,
(Class<? extends T[]>) a.getClass());
System.arraycopy(this.a, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
public E get(int index) {
return a[index];
}
public E set(int index, E element) {
E oldValue = a[index];
a[index] = element;
return oldValue;
}
public int indexOf(Object o) {
if (o==null) {
for (int i=0; i<a.length; i++)
if (a[i]==null)
return i;
} else {
for (int i=0; i<a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
public boolean contains(Object o) {
return indexOf(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}
*
* <p>This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
* <p>This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
throw new UnsupportedOperationException();
}
|
,而該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來源進一步說明