gpt4 book ai didi

java - T[] toArray(T 数组[])

转载 作者:行者123 更新时间:2023-11-29 07:13:59 26 4
gpt4 key购买 nike

有人可以在 Java Collection Framework 中解释一下 <T> 的重要性吗?在签名中

<T> T[] toArray(T array[]).

我知道<T>代表通用。但是基于示例的详尽解释将有很大帮助。

最佳答案

此方法允许您创建所需类型的数组。默认的 toArray() 返回 Object[],如果你有字符串列表并且你想从中得到一个 String[],这会很麻烦。

例如:

List<String> list = new ArrayList<>();        
list.add("A");

String[] listToArray;
listToArray = list.toArray(); // This won't compile as to Array gives Object[]

listToArray = list.toArray(new String[list.size()]); // This works when I want String[]

关于java - <T> T[] toArray(T 数组[]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11323652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com