List与Array转换

List to Array

List 提供了toArray的接口,所以可以直接调用转为object型数组:

List list = new ArrayList();
Object[] array=list.toArray();

上述方法存在强制转换时会抛异常,下面此种方式更推荐,可以指定类型:

String[] array=list.toArray(new String[list.size()]);

 

Array to List

最简单的方法似乎是这样:

String[] array = {"java", "c"};
List list = Arrays.asList(array);
//但该方法存在一定的弊端,返回的list是Arrays里面的一个静态内部类,该类并未实现add,remove方法,因此在使用时存在局限性

解决方案:

1、运用ArrayList的构造方法是目前来说最完美的作法,代码简洁,效率高:List list = new ArrayList(Arrays.asList(array));

List list = new ArrayList(Arrays.asList(array));

//ArrayList构造方法源码
public ArrayList(Collection c) {
    elementData = c.toArray();
    size = elementData.length;
    // c.toArray might (incorrectly) not return Object[] (see 6260652)
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, size, Object[].class);
}

2、运用Collections的addAll方法也是不错的解决办法。

List list = new ArrayList(array.length);
Collections.addAll(list, array);

 

Arrays.asList(T... a)源码:

public static  List asList(T... a) {
//  注意该ArrayList并非java.util.ArrayList
//  java.util.Arrays.ArrayList.ArrayList(T[])
    return new ArrayList<>(a);
}

private static class ArrayList extends AbstractList
    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[] toArray(T[] a) {
        int size = size();
        if (a.length < size)
            return Arrays.copyOf(this.a, size,
                                    (Class) 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

 

你可能感兴趣的:(集合)