方法一:使用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&lt;String&gt; 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转数组)

将java中数组转换为ArrayList的方法实例(包括ArrayList转数组)的更多相关文章

  1. Java中Pattern类的quote方法将任何字符串(包括正则表达式)都转换成字符串常量,不具有任何匹配功能

    Java中Pattern类的quote方法将任何字符串(包括正则表达式)都转换成字符串常量,不具有任何匹配功能. 下面是个例子: import org.junit.Test; import java. ...

  2. 关于java中的hashcode和equals方法原理

    关于java中的hashcode和equals方法原理 1.介绍 java编程思想和很多资料都会对自定义javabean要求必须重写hashcode和equals方法,但并没有清晰给出为何重写此两个方 ...

  3. Java中的栈,堆,方法区和常量池

    要说Java中的栈,堆,方法区和常量池就要提到HotSpot,HotSpot是Sun JDK 和 Open JDK中所带的虚拟机. (Sun JDK 和 Open JDK除了注释不同,代码实现基本上是 ...

  4. java中String对象的split方法

    在java.lang包中有String.split()方法,返回是一个String[]数组,今天碰到一个自己没注意的问题: 1.特殊分隔符 String str1 = "123|456|78 ...

  5. Java 中extends与implements使用方法

    Java 中extends与implements使用方法 标签: javaclassinterfacestring语言c 2011-04-14 14:57 33314人阅读 评论(7) 收藏 举报 分 ...

  6. Java中的equals和hashCode方法

    本文转载自:Java中的equals和hashCode方法详解 Java中的equals方法和hashCode方法是Object中的,所以每个对象都是有这两个方法的,有时候我们需要实现特定需求,可能要 ...

  7. Java中各种(类、方法、属性)访问修饰符与修饰符的说明

    类: 访问修饰符 修饰符 class 类名称 extends 父类名称 implement 接口名称 (访问修饰符与修饰符的位置可以互换) 访问修饰符 名称 说明 备注 public 可以被本项目的所 ...

  8. Java中替换HTML标签的方法代码

    这篇文章主要介绍了Java中替换HTML标签的方法代码,需要的朋友可以参考下 replaceAll("\\&[a-zA-Z]{0,9};", "").r ...

  9. java中需要关注的3大方面内容/Java中创建对象的几种方法:

    1)垃圾回收 2)内存管理 3)性能优化 Java中创建对象的几种方法: 1)使用new关键字,创建相应的对象 2)通过Class下面的new Instance创建相应的对象 3)使用I/O流读取相应 ...

随机推荐

  1. 配置Gitlab使用LDAP认证

    1. 通过SSH登陆Gitlab服务器. 2. 进行以下配置文件夹. [root@c720141 ~]# cd /etc/gitlab/ 3. 打开gitlab.rb配置文件,并加入以下配置. git ...

  2. 【LeetCode】170. Two Sum III – Data structure design

    Difficulty:easy  More:[目录]LeetCode Java实现 Description Design and implement a TwoSum class. It should ...

  3. POJ - 2115C Looooops 扩展欧几里得(做的少了无法一眼看出)

    题目大意&&分析: for (variable = A; variable != B; variable += C) statement;这个循环式子表示a+c*n(n为整数)==b是 ...

  4. linux cudnn安装

    cudnn-8.0-linux-x64-v5.1链接:http://pan.baidu.com/s/1c1JuMty 密码:v0g9 #以CuDNN的v5.1版本,Cuda 8.0为例 sudo ta ...

  5. 跟厂长学PHP7内核(七):常见变量类型的基本结构

    上篇文章讲述了变量的存储结构zval,今天我们就来学习一下几个常见变量类型的基本结构. 一.类型一览 zval中的u1.v.type用来存储变量的类型,而zval.value存储的是不同类型对应的值, ...

  6. 【Ray Tracing in One Weekend 超详解】 光线追踪1-1

    Preface 从这一篇起,我们开始学光线追踪这门牛逼的技术.读了几天,一个字:强! 这一篇我们主要讲述技术入门和一些简单的案例. 我们先学这本: Ready 这本书需要ppmview这个软件帮忙看效 ...

  7. python文件相关操作

    Python文件相关操作 打开文件 打开文件,采用open方法,会将文件的句柄返回,如下: f = open('test_file.txt','r',encoding='utf-8') 在上面的代码中 ...

  8. leetcode 两数之和 python

      两数之和     给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 1 ...

  9. android activity 启动模式

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 1,标准的, 2,单个 顶部 3,单个 任务 4,单个 实例 标准的 就是 每启动一次这 ...

  10. Codeforces Round #371 (Div. 2) D. Searching Rectangles 交互题 二分

    D. Searching Rectangles 题目连接: http://codeforces.com/contest/714/problem/D Description Filya just lea ...