collection.toArray(new String[0])

Collection的公有方法中,toArray()是比较重要的一个。

  • 但是使用无参数的toArray()有一个缺点,就是转换后的数组类型是Object[]。 虽然Object数组也不是不能用,但当你真的想用一个具体类型的数组,比如String[]时,问题就来了。而把Object[]给cast成 String[]还是很麻烦的,需要用到这个:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
  • 用带参数的toArray就好了。官方是这样给出的例子:
String[] a = c.toArray(new String[0]);

如果指定的数组能容纳该 collection,则返回包含此 collection 元素的数组。否则,将根据指定数组的运行时类型和此 collection 的大小分配一个新数组。这里给的参数的数组长度是0,因此就会返回包含此 collection 中所有元素的数组,并且返回数组的类型与指定数组的运行时类型相同

 public void test4(){
        HashMap<String,String> map=new HashMap<>();
        map.put("1","jk");
        map.put("2","kjk");
        String[] array = map.keySet().toArray(new String[3]);//1,2,null
        for (String a:array) {
            System.out.println(a);
        }
    }
  • 底层
    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;
            }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值