网站首页 > 知识剖析 正文
还有其他的方法,这里我列出最简单的方法来实现。
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);
}
输出结果:
猜你喜欢
- 2025-01-20 Excel中的6个经典排序技巧都不掌握,还敢称Excel达人?
- 2025-01-20 查询函数Choose、Lookup、Hlookup、Vlookup应用技巧解读
- 2025-01-20 一起学《C程序设计》第六课——数组、字符串及实战练习
- 2025-01-20 一文解决CSP-J考纲所有排序算法
- 2025-01-20 Excel VBA 自定义函数/数组字段定位/数组字段排序
- 2025-01-20 java基础,arrays类,Java的八种排序,冒泡排序
- 2025-01-20 excel中什么是数组,数组的作用是什么,这篇文章就带你入门
- 2025-01-20 16.9 数组 - 数据排序技术
- 2025-01-20 怎么求第K大的数,topK 问题(快排的应用)java
- 2025-01-20 VBA按日期统计就餐时段刷卡及人数(数组字典内置函数去重排序)
- 04-29php开发者composer使用看这一篇就够了
- 04-29引用和变量声明在不同语言中的实作
- 04-29PHP 没你想的那么差
- 04-29Ubuntu linux 上的 Nginx 和 Php 安装
- 04-29CentOS下通过yum搭建lnmp(单版本PHP)
- 04-29为什么 PHP8 是个高性能版本
- 04-29PHP8函数包含文件-PHP8知识详解
- 04-29使用无参数函数进行命令执行
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)