int[] array = {1,2,3,4,5}; //静态初始化 int[] array = new int[10]; //动态初始化,包含默认初始化 int[0]=10; //...
数组本身就是对象,Java中的对象是在堆中的,因此数组无论保存原始类型还是其他对象类型,数组对象本身是在堆中的。
int[4][2] array = {{1,2},{3,4},{5,6},{7,8}}; //遍历二维数组 for(int i = 0;i < array.length;i++){ for(int j = 0;i < array[i].length;j++){ System.out.print(array[i][j] + " "); } }
常用方法举例
Arrays.sort(a); //给a数组排序 Arrays.fill(a,0); //用0填充a数组 Arrays.fill(a,2,4,1); //用1填充a数组下标[2,4) Arrays.toString(a); //打印数组a 即将a数组的所有元素以一个String类型的字符串返回 //...
public class Dome{ public static void main(String[] args) { int[][] arrays = new int[11][11]; arrays[1][2]=1; arrays[2][3]=2; System.out.println("原数组:"); for (int i = 0; i <arrays.length ; i++) { for (int j = 0; j <arrays[i].length ; j++) { System.out.print(arrays[i][j]+"\t"); } System.out.println(); } int sum=0; for (int i = 0; i <arrays.length ; i++) { for (int j = 0; j <arrays[i].length ; j++) { if(arrays[i][j]!=0){ sum++; } } } int[][] arrays2 = new int[sum+1][3]; arrays2[0][0]=arrays.length; arrays2[0][1]=arrays.length; arrays2[0][2]=sum; int count = 0; for (int i = 0; i <arrays.length ; i++) { for (int j = 0; j <arrays[i].length ; j++) { if(arrays[i][j]!=0){ count++; arrays2[count][0]=i; arrays2[count][1]=j; arrays2[count][2]=arrays[i][j]; } } } System.out.println("===================="); System.out.println("稀疏数组:"); for (int i = 0; i <arrays2.length ; i++) { for (int j = 0; j <arrays2[i].length ; j++) { System.out.print(arrays2[i][j]+"\t"); } System.out.println(); } System.out.println("==========================="); System.out.println("复原后:"); int[][] arrays3 = new int[arrays2[0][0]][arrays2[0][1]]; for (int i = 1; i < arrays2.length ; i++) { arrays3[arrays2[i][0]][arrays2[i][1]] = arrays2[i][2]; } for (int i = 0; i <arrays3.length ; i++) { for (int j = 0; j <arrays3[i].length ; j++) { System.out.print(arrays3[i][j]+"\t"); } System.out.println(); } } }
结果: