Java toArray(new String[0]); 中 new String[0] 有什么用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18136437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:39:31  来源:igfitidea点击:

What's the use of new String[0] in toArray(new String[0]);

javaandroid

提问by user2580401

hi I have something like this:

嗨,我有这样的事情:

saved = getSharedPreferences("searches", MODE_PRIVATE);
String[] mystring = saved.getAll().keySet().toArray(new String[0]);

why do we need the argument new String[0]inside toArray?

为什么我们需要new String[0]里面的参数toArray

采纳答案by Rohit Jain

So that you get back a String[]. The one without any argument gives back to you an Object[].

以便您取回String[]. 没有任何争论的人会给你一个Object[].

See you have 2 versions of this method:

看看你有这个方法的 2 个版本:

By passing String[]array, you are using the generic version.

通过传递String[]数组,您使用的是通用版本。



A better way to pass the String[]array would be to initialize it with the size of the Set, and not with size 0, so that there is not need to create a new array in the method:

传递String[]数组的更好方法是使用 的大小初始化它Set,而不是大小为 0,这样就不需要在方法中创建新数组:

Set<String> set = saved.getAll().keySet();
String[] mystring = set.toArray(new String[set.size()]);

回答by AdamSpurgin

It's to provide a type for the return and prevent any compile-time ambiguity.

它是为返回提供类型并防止任何编译时歧义。

the signiture for that method call is: <T> T[] toArray(T[] a)

该方法调用的签名是: <T> T[] toArray(T[] a)

wheras the empty parameter one is Object[] toArray()

而空参数之一是 Object[] toArray()