Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 64e801e

Browse files
Add: Collection.toArray()
1 parent e2b97af commit 64e801e

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

‎docs/java/Java疑难点.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
- [《阿里巴巴Java 开发手册》对其的描述](#阿里巴巴java-开发手册对其的描述)
66
- [使用时的注意事项总结](#使用时的注意事项总结)
77
- [如何正确的将数组转换为ArrayList?](#如何正确的将数组转换为arraylist)
8+
- [`Collection.toArray()`方法使用的坑&如何反转数组](#collectiontoarray方法使用的坑如何反转数组)
89

910
<!-- /TOC -->
1011

@@ -194,3 +195,17 @@ List<String> list = new ArrayList<String>();
194195
CollectionUtils.addAll(list, str);
195196
```
196197

198+
## `Collection.toArray()`方法使用的坑&如何反转数组
199+
200+
该方法是一个泛型方法:`<T> T[] toArray(T[] a);` 如果`toArray`方法中没有传递任何参数的话返回的是`Object`类型数组。
201+
202+
```java
203+
String [] s= new String[]{
204+
"dog", "lazy", "a", "over", "jumps", "fox", "brown", "quick", "A"
205+
};
206+
List<String> list = Arrays.asList(s);
207+
Collections.reverse(list);
208+
s=list.toArray(new String[0]);//没有指定类型的话会报错
209+
```
210+
211+
由于JVM优化,`new String[0]`作为`Collection.toArray()`方法的参数现在使用更好,`new String[0]`就是起一个模板的作用,指定了返回数组的类型,0是为了节省空间,因为它只是为了说明返回的类型。详见:<https://shipilev.net/blog/2016/arrays-wisdom-ancients/>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /