您的位置:首页 > 编程语言 > Java开发

将java中数组转换为ArrayList的方法实例(包括ArrayList转数组)

2017-06-26 23:21 537 查看

方法一:使用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来源进一步说明

转载请注明:大步's Blog » 将java中数组转换为ArrayList的方法实例(包括ArrayList转数组)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: