1 数组的复制
代码语言:java复制package cc.linuxcc.array;
public class ArrayCopy {
public static void main(String[] args) {
int arr1[] = {1,2,3,4,5};
int arr2[] = new int[arr1.length];
for (int i = 0; i < arr1.length; i ) {
arr2[i] = arr1[i]; // 把arr1的值复制给arr2
}
System.out.println("------Arr2------");
System.out.println("Arr2的地址值是:" arr2);
for (int i = 0; i < arr2.length; i ) {
System.out.println(arr2[i]);
}
System.out.println("------Arr1------");
System.out.println("Arr1的地址值是:" arr1);
for (int i = 0; i < arr1.length; i ) {
System.out.println(arr1[i]);
}
}
}
2 数组反转
代码语言:java复制package cc.linuxcc.array;
public class ArrayReverse {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
int tmp;
int arrayLength = arr.length;
for (int i = 0; i < arrayLength / 2; i ) {
// arrayLength = 6;
// 第一次循环 i = 0, 6 - 1 - 0 = 6;
// 第二次循环 i = 1, 6 - 1 - 1 = 5;
// 第三次循环 i = 2, 6 - 1 - 2 = 4;
tmp = arr[arrayLength - 1 - i]; // 把数组中最后一个元素赋给临时变量
arr[arrayLength - 1 - i] = arr[i]; // 把数组中第一个值赋值给最后一个index的位置
arr[i] = tmp; // 把临时变量赋值给数组中index=0那个位置
}
for (int i = 0; i < arr.length; i ) {
System.out.print(arr[i] " ");
}
}
}
运行结果 7 6 5 4 3 2 1
3 逆序法
代码语言:java复制package cc.linuxcc.array;
public class ArrayReverse02 {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
int[] tmpArray = new int[arr.length]; // 新建临时数组
// 循环赋值 这里用变量j作为临时变量的索引
for (int i = arr.length - 1, j = 0; i >= 0; i--, j ) {
tmpArray[j] = arr[i];
}
// 把tmpArray的地址值赋值给arr
arr = tmpArray;
System.out.println("=============逆序赋值法===============");
for (int i = 0; i < arr.length; i ) {
System.out.print(arr[i] " ");
}
}
}