zoukankan      html  css  js  c++  java
  • java中数组与List相互转换的方法

    1.List转换成为数组。(这里的List是实体是ArrayList)

      调用ArrayList的toArray方法。

      toArray

      public <T> T[] toArray(T[] a)返回一个按照正确的顺序包含此列表中所有元素的数组;返回数组的运行时类型就是指定数组的运行时类型。如果列表能放入指定的数组,则返回放入此列表元素的数组。否则,将根据指定数组的运行时类型和此列表的大小分配一个新的数组。

      如果指定的数组能容纳列表并有剩余空间(即数组的元素比列表的多),那么会将数组中紧跟在集合末尾的元素设置为 null。这对确定列表的长度很有用,但只 在调用方知道列表中不包含任何 null 元素时才有用。

      指定者:

      接口 Collection<E> 中的 toArray

      指定者:

      接口 List<E> 中的 toArray

      覆盖:

      类 AbstractCollection<E> 中的 toArray

      参数:

      a - 要存储列表元素的数组,如果它足够大的话;否则,它是一个为存储列表元素而分配的、具有相同运行时类型的新数组。

      返回:

      包含列表元素的数组。

      抛出:

      ArrayStoreException - 如果 a 的运行时类型不是此列表中每个元素的运行时类型的超类型。

      具体用法:

    List list = new ArrayList(); list.add("1"); list.add("2"); final int size = list.size(); String[] arr = (String[])list.toArray(new String[size]);

    2.数组转换成为List。

      调用Arrays的asList方法.

      asList

      public static <T> List<T> asList(T... a)返回一个受指定数组支持的固定大小的列表。(对返回列表的更改会“直写”到数组。)此方法同 Collection.toArray 一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的,并且实现了 RandomAccess。

      此方法还提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素:

       List stooges = Arrays.asList("Larry", "Moe", "Curly");

      参数:

      a - 支持列表的数组。

      返回:

      指定数组的列表视图。

      另请参见:

      Collection.toArray()

      具体用法:

      String[] arr = new String[] {"1", "2"};

      List list = Arrays.asList(arr);

    测试代码如下:

    @Test
     public void demo9(){
      List<String> list = new ArrayList<String>();
      list.add("sx");
      list.add("shi");
      Object[] array = list.toArray();
      for (Object object : array) {
       System.out.println(object);
      }  
      List<Object> asList = Arrays.asList(array);
      for (Object object : asList) {
       System.out.println(object);
      }
     }

  • 相关阅读:
    Lintcode423-Valid Parentheses-Easy
    Lintcode97-Maximum Depth of Binary Tree-Easy
    Lintcode175-Revert Binary Tree-Easy
    Lintcode469-Same Tree-Easy
    Leetcode480-Binary Tree Paths-Easy
    Lintcode481-Binary Tree Leaf Sum-Easy
    Lintcode482-Binary Tree Level Sum-Easy
    Lintcode376-Binary Tree Path Sum-Easy
    SQL
    Database
  • 原文地址:https://www.cnblogs.com/sxshiblog/p/4204799.html
Copyright © 2011-2022 走看看