在Set toArray()方法中需要新的String [0] [英] Need for new String[0] in the Set toArray() method

查看:95
本文介绍了在Set toArray()方法中需要新的String [0]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Set转换为数组.

I am trying to convert a Set to an Array.

Set<String> s = new HashSet<String>(Arrays.asList("mango","guava","apple"));
String[] a = s.toArray(new String[0]);
for(String x:a)
      System.out.println(x);

它工作正常.但是我不理解 String [] a = s.toArray(new String [0]); new String [0] 的重要性.

And it works fine. But I don't understand the significance of new String[0] in String[] a = s.toArray(new String[0]);.

我的意思是,最初我尝试使用 String [] a = c.toArray(); ,但是它不起作用.为什么需要 new String [0] .

I mean initially I was trying String[] a = c.toArray();, but it wan't working. Why is the need for new String[0].

推荐答案

如果Set足够大,则是将Set的元素存储到的数组;否则,将为此分配一个具有相同运行时类型的新数组.

It is the array into which the elements of the Set are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Object [] toArray(),返回一个不能转换为 String [] 或任何其他类型数组的 Object [] .

Object[] toArray(), returns an Object[] which cannot be cast to String[] or any other type array.

T [] toArray(T [] a)返回包含此集合中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型.如果集合适合指定的数组,则将其返回.否则,将使用指定数组的运行时类型和该集合的大小分配一个新数组.

如果您查看实施代码(我正在从

If you go through the implementing code (I'm posting the code from OpenJDK) , it will be clear for you :

 public <T> T[] toArray(T[] a) {
     if (a.length < size)
     // Make a new array of a's runtime type, but my contents:
     return (T[]) Arrays.copyOf(elementData, size, a.getClass());
     System.arraycopy(elementData, 0, a, 0, size);
     if (a.length > size)
         a[size] = null;
    return a;
 }

这篇关于在Set toArray()方法中需要新的String [0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆