1.数组的声明
int[] arr = new int[10]; int brr[] = new int[10];
2.数组初始化
public class Demo10 { public static void main(String[] args) { //01 静态初始化 int[] a = {1,2,3}; //02 动态初始化:包含默认初始化 int[] b = new int[3]; b[0] = 1; } }
3.数组的四个特点(数组是相同数据类型的有序集合)
4.数据的使用
public class Demo11 { public static void main(String[] args) { int[] arr = {1,2,3,4,5}; //打印数组元素 for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } //for each for (int x:arr) { System.out.println(x); } //接受翻转数组 int[] crr = fun(arr); for (int x:crr) { System.out.print(x); } } //翻转数组 public static int[] fun(int[] arr){ int[] brr = new int[arr.length]; for (int i = 0,j = brr.length - 1;i < arr.length;i++,j--){ brr[j] = arr[i]; } return brr; } }
5.Array类的使用
6.冒泡排序
public class Demo12 { public static void main(String[] args) { int[] a = {1,23,21,333,123}; for (int i = 0;i < a.length;i++){ for (int j = 0;j < a.length - 1 - i;j++){ if (a[j] > a[j + 1]){ int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; } } } for (int x:a) { System.out.println(x); } } }
7.稀疏数组
public class Demo13 { public static void main(String[] args) { //创建一个二维数组11*11 int[][] arr1 = new int[11][11]; arr1[1][2] = 1; arr1[2][3] = 2; //输出原始数组 System.out.println("输出原始数组:"); for (int[] a1:arr1) { for (int a2:a1) { System.out.print(a2 + "\t"); } System.out.println(); } System.out.println("========================================="); //转换为稀疏数组 //获取有效值个数 int sum = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if(arr1[i][j] != 0){ sum++; } } } System.out.println("有效值个数:" + sum); //创建一个稀疏数组 int[][] arr2 = new int[sum + 1][3]; arr2[0][0] = 11; arr2[0][1] = 11; arr2[0][2] = sum; //遍历数组,把有效值存到稀疏数组 int count = 0; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { if (arr1[i][j] != 0){ count++; arr2[count][0] = i; arr2[count][1] = j; arr2[count][2] = arr1[i][j]; } } } System.out.println("========================================="); //输出稀疏数组 System.out.println("稀疏数组:"); for (int i = 0; i < arr2.length; i++) { System.out.println(arr2[i][0] + "\t" + arr2[i][1] + "\t" + arr2[i][2]); } System.out.println("========================================="); System.out.println("还原:"); //1.读取稀疏数组 int[][] arr3 = new int[arr2[0][0]][arr2[0][1]]; for (int i = 1;i < arr2[0][2] + 1;i++){ arr3[arr2[i][0]][arr2[i][1]] = arr2[i][2]; } for (int[] a1:arr3) { for (int a2:a1) { System.out.print(a2 + "\t"); } System.out.println(); } } }
原文:https://www.cnblogs.com/yyj0702/p/14685722.html