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方法,因此在使用时存在局限性

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

 

解决方案:

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);

 

https://www.cnblogs.com/goloving/p/7740100.html

相关文章:

  • 2021-12-18
  • 2021-07-03
  • 2022-01-12
  • 2021-07-27
  • 2021-12-18
  • 2021-07-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-13
  • 2021-07-25
  • 2021-12-28
  • 2022-02-21
  • 2022-12-23
相关资源
相似解决方案