java数组插入元素的方法有哪些
作者:BrightSoul
时间:2023-04-24
来源:互联网
浏览:0
1、使用insertElement()方法向数组插入元素importjava.util.Arrays;publicclassTest{publicstaticvoidmain(Stringargs[])throwsException{intarray[]={2,5,-2,6,-3,8,0,-7,-9,4};Arrays.sort(array);intindex=Arrays.binarySearch(array,1);System.out.println("元素1所在位置(负数为不存在):"+index)
1、使用 insertElement () 方法向数组插入元素
import java.util.Arrays;
public class Test{
public static void main(String args[]) throws Exception {
int array[] = {
2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
int index = Arrays.binarySearch(array, 1);
System.out.println("元素 1 所在位置(负数为不存在):"
+ index);
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
System.out.println("添加元素1后:"+Arrays.toString(array));
}
private static int[] insertElement(int original[],
int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index
+ 1, length - index);
return destination;
}
}
/* 输出结果:
元素 1 所在位置(负数为不存在):-6
添加元素1:[-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8]
*/2、把数组转化为集合,向集合中添加元素,再将集合转化为数组
import java.util.*;
public class Test{
public static void main(String[] args) {
String[] arr = {
"ID", "姓名"};
// 将数组转化为集合 1
List list1 = Arrays.asList(arr);
List list2 = new ArrayList<>();
// 定义集合 2 、并向其中添加元素: 性别
list2.add("性别");
List List = new ArrayList();
// 定义新集合、将集合1、2中的元素添加到新集合
List.addAll(list1);
List.addAll(list2);
// 将新集合转化回新数组
String[] newArr = List.toArray(new String[List.size()]);
System.out.println(Arrays.toString(newArr));
}
}
/* 输出结果: [ID, 姓名, 性别] */ 3、创建一个新数组,新数组的大小为旧数组大小+1,把旧数组里的元素copy一份进新数组,并把要添加的元素添加进新数组即可。
作者最新文章
索尼 Xperia 1 VIII / VII / VI 等手机获 Android 17 更新,新增桌面模式等功能
2026-09-08 16:44
加拿大留学监护声明书(IMM 5646)双页签署与公证核对指南
2026-09-03 15:02
在线PDF转图片教程:一键生成高清图片包
2026-09-03 12:04
Creo零基础入门:新建零件与第一次拉伸建模完整指南
2026-09-03 06:02
扫描件PDF转Word的在线操作步骤与编辑可行性判断
2026-09-02 18:39
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















