1、源码
package com.study.sparsearray;import java.io.*;public class SparseArray2 {public static void main(String[] args) throws IOException {//创建一个11*11的二维数组int chessArr1[][] = new int[11][11];//给数组赋值chessArr1[1][2]=1;chessArr1[2][3]=2;chessArr1[3][4]=3;chessArr1[4][5]=4;//遍历数组for (int[] arr : chessArr1) {for (int data : arr) {System.out.print("\t"+data);}System.out.println();}//获取数组中不为0的数的个数int sum =0;for (int i = 0; i < 11; i++) {for (int j = 0; j < 11; j++) {if(chessArr1[i][j]!=0){sum++;}}}//将二维数组转换成稀疏数组 (sum+1)*3int sparseArr1[][] = new int[sum+1][3];sparseArr1[0][0]=11;sparseArr1[0][1]=11;sparseArr1[0][2]=sum;int count=1;for (int i = 0; i < 11; i++) {for (int j = 0; j < 11; j++) {if(chessArr1[i][j]!=0){sparseArr1[count][0]=i;sparseArr1[count][1]=j;sparseArr1[count][2]=chessArr1[i][j];count++;}}}//遍历稀疏数组System.out.println("sparseArr1为:");for (int[] arr : sparseArr1) {for (int data : arr) {System.out.print("\t"+data);}System.out.println();}//将稀疏数组存到文件中FileWriter fw = new FileWriter("SparseArray2");for (int i = 0; i < sparseArr1.length; i++) {for (int j = 0; j < 3; j++) {fw.write(sparseArr1[i][j]+"\t");}fw.write("\r\n");}fw.close();//从文件中将稀疏数组读取出来BufferedReader br = new BufferedReader(new FileReader("SparseArray2"));String line;int row=0;int sparseArr2[][] = new int[sum+1][3];while (((line=br.readLine())!=null)){String[] s = line.split("\t");for (int i = 0; i < s.length; i++) {sparseArr2[row][i]=Integer.parseInt(s[i]);}row++;}br.close();//将sparseArr2遍历System.out.println("sparseArr2为:");for (int[] arr : sparseArr2) {for (int data : arr) {System.out.print("\t"+data);}System.out.println();}//将从文件读取的稀疏数组转换成二维数组int chessArr2[][] = new int[sparseArr2[0][0]][sparseArr2[0][1]];for (int i = 1; i < sparseArr2.length; i++) {chessArr2[sparseArr2[i][0]][sparseArr2[i][1]] = sparseArr2[i][2];}for (int[] arr : chessArr2) {for (int data : arr) {System.out.print("\t"+data);}System.out.println();}}}
2、运行结果

3、总结
二维数组 转 稀疏数组的思路
- 遍历 原始的二维数组,得到有效数据的个数 sum
- 根据sum 就可以创建 稀疏数组 sparseArr int[sum + 1] [3]
- 将二维数组的有效数据数据存入到 稀疏数组
稀疏数组转原始的二维数组的思路
- 先读取稀疏数组的第一行,根据第一行的数据,创建原始的二维数组,比如上面的 chessArr2 = int [11][11]
- 在读取稀疏数组后几行的数据,并赋给 原始的二维数组 即可.
4、扩展
将稀疏数组存储到文件中,并读取出来
//将稀疏数组存到文件中
FileWriter fw = new FileWriter("SparseArray2");
for (int i = 0; i < sparseArr1.length; i++) {
for (int j = 0; j < 3; j++) {
fw.write(sparseArr1[i][j]+"\t");
}
fw.write("\r\n");
}
fw.close();
//从文件中将稀疏数组读取出来
BufferedReader br = new BufferedReader(new FileReader("SparseArray2"));
String line;
int row=0;
int sparseArr2[][] = new int[sum+1][3];
while (((line=br.readLine())!=null)){
String[] s = line.split("\t");
for (int i = 0; i < s.length; i++) {
sparseArr2[row][i]=Integer.parseInt(s[i]);
}
row++;
}
br.close();
