public class demo04 {
public static void main(String[] args) {
int[][] arr1 = new int[11][11];
arr1[1][2] = 1;
arr1[2][3] = 1;
for (int[] ints : arr1) {
for (int anInt : ints) {
System.out.print(anInt+"\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++;
}
}
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];
}
}
}
for (int[] ints : arr2) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
System.out.println("======================");
//将稀疏数组转化为普通数组
int[][] arr3 = new int[arr2[0][0]][arr2[0][1]];
for (int i = 1; i < arr2.length; i++){
arr3[arr2[i][0]][arr2[i][1]] = arr2[i][2];
}
for (int[] ints : arr3) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
}
}
输出结果: