直接上代码…
package com.itheima.Servlet.demo;
import org.junit.Test;
public class demo {
@Test
public void test1() {
int[][] arr = new int[11][11];
arr[1][2] = 1;
arr[2][3] = 2;
arr[3][4] = 2;
arr[4][5] = 2;
for (int[] a : arr) {
for (int i : a) {
System.out.print(i + "\t");
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] != 0){
sum++;
}
}
}
System.out.println("非0数为"+sum+"个");
int xArr[][] = new int[sum+1][3];
xArr[0][0] = 11;
xArr[0][1] = 11;
xArr[0][2] = sum;
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] != 0){
count++;
xArr[count][0] = i;
xArr[count][1] = j;
xArr[count][2] = arr[i][j];
}
}
}
System.out.println("-----------------------");
for (int[] ints : xArr) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
System.out.println("--------------以上部分是将二维数组转成稀疏数组---------------");
System.out.println("--------------以下部分是将稀疏数组转成二维数组---------------");
int[][] arr2 = new int[xArr[0][0]][xArr[0][1]];
System.out.println("稀疏数组转成二维数组之后...");
for (int[] ints : arr2) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
for (int i = 1; i < xArr.length; i++) {
arr2[xArr[i][0]][xArr[i][1]] = xArr[i][2];
}
System.out.println("生成的二维数组是...");
for (int[] ints : arr2) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
}
}