暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Java List集合转数组的两种重载方法

11048

前几天写代码碰到了这个场景,要将一个List转换成数组,

    List<String> list = new ArrayList<String>();
    ...
    list.add(...);
    ...
    JSONObject obj = new JSONObject();
    obj.put("result", list.toArray());
    复制

    ArrayList提供了将List转为数组的简单方法toArray,他有两个重载的方法,

    (1) list.toArray();,将list直接转为Object[]数组。

    (2) list.toArray(T[] a);,将list转换为你所需要类型的数组,我们用的时候会转换为与list内容相同的类型。

    像我这种不明真相的朋友,可能选择第一个,毕竟看着简单,

      ArrayList<String> list=new ArrayList<String>();
      for (int i = 0; i < 10; i++) {
      list.add(""+i);
      }
      String[] array= (String[]) list.toArray();
      复制

      但是运行起来,就会提示,

        Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; 
        cannot be cast to [Ljava.lang.String;
        复制

        原因很清楚,不能将Object[]转换为String[],如果要转换,只可以取出每一个元素,再进行转换,因为在Java中的强制类型转换只是针对单个对象的,不能将整个数组转换成另外一种类型的数组,

          Object[] arr = list.toArray();
          for (int i = 0; i < arr.length; i++) {
          String e = (String) arr[i];
          System.out.println(e);
          }
          复制

          因此,我们转向第二种,

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

            最开始的示例,使用第二种重载,如下所示,

              List<String> list = new ArrayList<String>();
              ...
              list.add(...);
              ...
              JSONObject obj = new JSONObject();
              obj.put("result", list.toArray(new String[list.size()]));
              复制

              从toArray()的help,我们看到,这种形式能准确地控制array的运行时类型,

              Like the toArray() method, this method acts as bridge betweenarray-based and collection-based APIs. Further, this method allows precise control over the runtime type of the output array, and may,under certain circumstances, be used to save allocation costs

              因此,当我们需要将集合转成数组的时候,尽量选择list.toArray(T[] a),避免不必要的类型转换错误。

              近期更新的文章:

              PG逻辑复制的REPLICA IDENTITY设置

              最近碰到的几个问题

              Linux的dd指令

              Oracle、SQL Server和MySQL的隐式转换异同

              JDK的版本号解惑


              文章分类和索引:

              公众号700篇文章分类和索引

              文章转载自bisal的个人杂货铺,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

              评论