【数据结构】数据
【摘要】 一、数组的定义数组是一种线性的数据结构,它是由相同类型的元素(如整数、浮点数、字符等)组成的有序集合。这些元素在内存中是连续存储的,通过索引(也称为下标)来访问各个元素。索引通常是从 0 开始的整数,例如在一个包含 n 个元素的数组中,索引的范围是 0 到 n - 1。例如,一个简单的整数数组int[] arr = {1, 2, 3, 4, 5};,这里arr是数组的名称,1、2、3、4、5...
public class ArrayExample {
public static void main(String[] args) {
// 创建一个整数数组
int[] arr = {1, 2, 3, 4, 5};
// 访问数组元素
System.out.println("第三个元素是:" + arr[2]);
// 在末尾插入元素
int[] newArr = new int[6];
System.arraycopy(arr, 0, newArr, 0, arr.length);
newArr[5] = 6;
System.out.println("在末尾插入元素后的数组:");
for (int i : newArr) {
System.out.print(i + " ");
}
System.out.println();
// 在中间插入元素
int[] anotherArr = new int[7];
System.arraycopy(newArr, 0, anotherArr, 0, 3);
anotherArr[3] = 7;
System.arraycopy(newArr, 3, anotherArr, 4, newArr.length - 3);
System.out.println("在中间插入元素后的数组:");
for (int i : anotherArr) {
System.out.print(i + " ");
}
System.out.println();
// 删除末尾元素
int[] tempArr = new int[anotherArr.length - 1];
System.arraycopy(anotherArr, 0, tempArr, 0, tempArr.length);
System.out.println("删除末尾元素后的数组:");
for (int i : tempArr) {
System.out.print(i + " ");
}
System.out.println();
// 删除中间元素
int[] finalArr = new int[tempArr.length - 1];
System.arraycopy(tempArr, 0, finalArr, 0, 3);
System.arraycopy(tempArr, 4, finalArr, 3, tempArr.length - 4);
System.out.println("删除中间元素后的数组:");
for (int i : finalArr) {
System.out.print(i + " ");
}
}
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)