List to Array
List 提供了toArray的接口,所以可以直接调用转为object型数组:
List<String> list = new ArrayList<String>();
Object[] array=list.toArray();
上述方法存在强制转换时会抛异常,下面此种方式更推荐,可以指定类型:
String[] array=list.toArray(new String[list.size()]);
Array to List
最简单的方法似乎是这样:
String[] array = {"java", "c"};
List<String> list = Arrays.asList(array);
//但该方法存在一定的弊端,返回的list是Arrays里面的一个静态内部类,该类并未实现add,remove方法,因此在使用时存在局限性
解决方案:
1、运用ArrayList的构造方法是目前来说最完美的作法,代码简洁,效率高:List<String> list = new ArrayList<String>(Arrays.asList(array));
List<String> list = new ArrayList<String>(Arrays.asList(array));
//ArrayList构造方法源码
public ArrayList(Collection<? extends E> 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<String> list = new ArrayList<String>(array.length);
Collections.addAll(list, array);
Arrays.asList(T... a)源码:
public static <T> List<T> asList(T... a) {
// 注意该ArrayList并非java.util.ArrayList
// java.util.Arrays.ArrayList.ArrayList<T>(T[])
return new ArrayList<>(a);
}
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;
}
}