Set toArray() 方法中需要 new String[0]

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

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

问题描述

我正在尝试将 Set 转换为 Array.

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

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元素的数组;否则,将为此目的分配一个相同运行时类型的新数组.

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(),返回一个 Object[] 不能转换为 String[] 或任何其他类型的数组.

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

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

如果您通过实现代码(我从 OpenJDK) ,你会很清楚:

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() 方法中需要 new String[0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Set toArray() 方法中需要 new String[0]

基础教程推荐