在实际开发中,虽然用集合(collection)来存储元素通常更灵活,但有些场景下,我们仍然需要将集合转换成数组(比如与老旧 api 交互、需要固定大小存储等)。
java 的 collection 接口提供了 三种方式 来实现这一点,都是通过 toarray() 方法的不同重载实现的。
🌟 三种toarray()使用方式
| 方法 | 返回 | 特点 |
|---|---|---|
| toarray() | object[] | 返回一个对象数组,不带类型信息 |
| toarray(t[] array) | t[] | 返回一个指定类型的数组,需要传入一个数组 |
| toarray(intfunction<t[]> generator) | t[] | 使用构造器引用创建数组,代码更简洁(jdk 8+) |
1. 🛠️ 使用无参toarray()
这种方式最简单:直接调用 toarray(),返回的是一个 object[] 类型的数组。
collection<string> strings = list.of("one", "two", "three");
object[] array = strings.toarray();
system.out.println(arrays.tostring(array));
🖨️ 输出结果:
[one, two, three]
⚠️ 注意: 这种方式得到的是 object[],如果你强制转换成 string[],可能会在运行时抛出异常(classcastexception)。 因此,一般不推荐在需要明确类型时使用这种方式。
2. 🛠️ 使用带数组参数的toarray(t[] array)
这种方式可以直接得到正确类型的数组,比如 string[],而且避免类型转换出错。
collection<string> strings = list.of("one", "two");
// 方式1:传入一个长度为0的数组
string[] result1 = strings.toarray(new string[0]);
system.out.println(arrays.tostring(result1));
// 方式2:传入一个足够大的数组
string[] largerarray = new string[5];
string[] result2 = strings.toarray(largerarray);
system.out.println(arrays.tostring(result2));
🖨️ 输出结果:
[one, two]
[one, two, null, null, null]
✨ 背后细节解释
- 如果传入的数组长度大于等于集合的大小,元素将被直接拷贝到这个数组中;
- 如果传入的数组长度小于集合的大小,java会创建一个新数组,大小正好适配集合元素;
- 如果数组比集合大,拷贝完元素后,第一个空余位置会设为
null,剩下的位置保持原值。
🔥 示例:传入比集合大的数组
collection<string> strings = list.of("one", "two");
string[] largertab = {"old1", "old2", "old3", "old4"};
system.out.println("before: " + arrays.tostring(largertab));
string[] result = strings.toarray(largertab);
system.out.println("after : " + arrays.tostring(result));
system.out.println("same array? " + (result == largertab));
🖨️ 输出结果:
before: [old1, old2, old3, old4]
after : [one, two, null, old4]
same array? true
✅ 注意:返回的是传入的原数组,而不是新建的数组!
3. 🛠️ 使用toarray(intfunction<t[]> generator)(推荐)
从 java 11 开始,你可以使用构造器引用(例如 string[]::new)来创建数组,更加优雅、简洁!
collection<string> strings = list.of("one", "two", "three");
string[] array = strings.toarray(string[]::new);
system.out.println(arrays.tostring(array));
🖨️ 输出结果:
[one, two, three]
🎯 小结
| 方法 | 优点 | 缺点 |
|---|---|---|
| toarray() | 简单直接 | 只返回 object[],需要小心类型 |
| toarray(t[] array) | 返回指定类型,兼容老版本java | 代码稍长,需要处理数组长度 |
| toarray(intfunction<t[]> generator) | 代码最简洁,推荐(java 11+) | 需要理解构造器引用语法 |
到此这篇关于java将集合元素转换为数组的三种方式的文章就介绍到这了,更多相关java 集合元素转换为数组内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论