网站首页 > 博客文章 正文
还有其他的方法,这里我列出最简单的方法来实现。
1、Java合并两个数组
第一种:
public static void main(String[] args) {
int[] a = new int[]{58, 64, 21, 0, 89, 31, 26};
int[] b = new int[]{6, 7, 8};
int[] c = new int[a.length + b.length];
int i;
for (i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int j = 0; j < b.length; j++) {
c[i + j] = b[j];
}
// 输出合并后的数组
System.out.println(Arrays.toString(c));
}
输出结果:
第二种:
public static void main(String[] args) {
// 两个待合并数组
int array1[] = {20,10,50,40,30};
int array2[] = {1,2,3};
// 动态初始化数组,设置数组的长度是array1和array2长度之和
int array[] = new int[array1.length + array2.length];
// 循环添加数组内容
for (int i = 0; i < array.length; i++) {
if (i < array1.length) {
array[i] = array1[i];
} else {
array[i] = array2[i - array1.length];
}
}
System.out.println("合并后:");
for (int element : array) {
System.out.printf("%d ", element);
}
}
输出结果:
2、Java数组排序并去重
public static void main(String[] args) {
/*
思路:
1.hashset去重
2.转成treeset排序
3.转成integer数组
4.转成int数组
5.输出
*/
Integer[] array = {1, 3, 4, 3, 2, 5, 6, 3, 9, 22};
//去重
HashSet<Integer> hashset = new HashSet<>();
for (int i = 0; i < array.length; i++) {
hashset.add(array[i]);
}
//转成TreeSet排序
TreeSet<Integer> treeSet = new TreeSet<>(hashset);
//转成integer数组
Integer[] integers = treeSet.toArray(new Integer[]{});
int[] ints = new int[integers.length];
//foreach仅可用于遍历输出数组,但不能用于修改数组。
for (int i = 0; i < integers.length; i++) {
ints[i] = integers[i].intValue();
}
// 使用JDK1.8新特性输出
Arrays.stream(ints).forEach(System.out::println);
}
输出结果:
猜你喜欢
- 2024-10-27 ES6扩展运算符:详解与实践(es6扩展运算符深拷贝)
- 2024-10-27 Excel|文本花样连接,CONCATENATE、CONCAT、TEXTJOIN帮你完成
- 2024-10-27 Javascript中数组的方法(javascript 数组方法)
- 2024-10-27 LeetCode题集-4 - 寻找两个有序数组的中位数,六种解法,万字讲解
- 2024-10-27 JS中的Array对象——数组的合并、转换、迭代、排序、堆栈
- 2024-10-27 JavaScript 数组方法的介绍(javascript数组方法有哪些)
- 2024-10-27 vue数组更新后不渲染页面与$set的渊源
- 2024-10-27 vue-router的基本使用(vue- router)
- 2024-10-27 ???数组中的逆序对(归并排序思想)
- 2024-10-27 数据分析工具:Pandas架构分析(pandas数据分析模型)
你 发表评论:
欢迎- 367℃用AI Agent治理微服务的复杂性问题|QCon
- 358℃初次使用IntelliJ IDEA新建Maven项目
- 357℃手把手教程「JavaWeb」优雅的SpringMvc+Mybatis整合之路
- 351℃Maven技术方案最全手册(mavena)
- 348℃安利Touch Bar 专属应用,让闲置的Touch Bar活跃起来!
- 346℃InfoQ 2024 年趋势报告:架构篇(infoq+2024+年趋势报告:架构篇分析)
- 345℃IntelliJ IDEA 2018版本和2022版本创建 Maven 项目对比
- 342℃从头搭建 IntelliJ IDEA 环境(intellij idea建包)
- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)