使用ArrayList合并:将两个字符串数组转为列表并添加至ArrayList,再转换回数组,代码清晰易懂;2. 使用System.arraycopy:创建新数组并通过系统调用复制元素,性能更高,适合大数组处理。

在Java中合并两个字符串数组,可以通过几种方式实现,最常见的是使用 ArrayList 或 Arrays.copyOf 和 System.arraycopy。下面介绍两种实用且易于理解的方法。
将两个数组的元素依次添加到一个 ArrayList 中,再转换回数组。这种方法代码清晰,适合大多数场景。
示例代码:
String[] array1 = {"a", "b", "c"};
String[] array2 = {"d", "e", "f"};
<p>List<String> list = new ArrayList<>(Arrays.asList(array1));
list.addAll(Arrays.asList(array2));</p><p>String[] merged = list.toArray(new String[0]);</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1098">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680092332148.png" alt="怪兽AI数字人">
</a>
<div class="aritcle_card_info">
<a href="/ai/1098">怪兽AI数字人</a>
<p>数字人短视频创作,数字人直播,实时驱动数字人</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="怪兽AI数字人">
<span>44</span>
</div>
</div>
<a href="/ai/1098" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="怪兽AI数字人">
</a>
</div>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p>说明:
- 先用 Arrays.asList() 将第一个数组转为列表;
- 添加第二个数组转换后的列表;
- 最后通过 toArray() 转回字符串数组。
如果你更关注性能,尤其是处理大数组时,可以使用 System.arraycopy() 手动复制元素。
String[] array1 = {"a", "b", "c"};
String[] array2 = {"d", "e", "f"};
<p>int len1 = array1.length;
int len2 = array2.length;
String[] merged = new String[len1 + len2];</p><p>System.arraycopy(array1, 0, merged, 0, len1);
System.arraycopy(array2, 0, merged, len1, len2);</p>说明:
- 创建一个新数组,长度为两个原数组之和;
- 第一次复制把 array1 内容放到前面;
- 第二次复制把 array2 放到后面位置。
基本上就这些。小项目用 ArrayList 更方便,对性能敏感时选 System.arraycopy。两种方法都可靠,根据习惯选择就行。
以上就是在Java中如何合并两个字符串数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号