图示原始数组和稀疏数组的转换过程
![](https://img2020.cnblogs.com/blog/1736534/202009/1736534-20200913162723477-835250048.png)
代码实现
public class SparseArray {
public static void main(String[] args) throws Exception {
// 1. 创建原始数组
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[4][5] = 2;
// 1.1 遍历输出原始数组
System.out.println("原始数组:");
travarseArrayPrint(chessArr1);
// 2. 将原始数组转换为稀疏数组
// 2.1 定义变量记录原始数组中非0元素的个数
int sum = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[0].length; j++) {
if (chessArr1[i][j] != 0) {
sum++;
}
}
}
// 2.2 创建稀疏数组并给稀疏数组赋值
int[][] sparseArr = new int[sum + 1][3];
// 2.3 给稀疏数组的第一行赋值
sparseArr[0][0] = chessArr1.length;
sparseArr[0][1] = chessArr1[0].length;
sparseArr[0][2] = sum;
// 2.4 定义变量记录稀疏数组的行数
int count = 0;
// 2.5 给稀疏数组第一行之后的行赋值
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[0].length; j++) {
if (chessArr1[i][j] != 0) {
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
}
}
}
// 2.6 遍历输出稀疏数组
System.out.println("稀疏数组:");
travarseArrayPrint(sparseArr);
// 2.7 将稀疏数组存入到磁盘文件
File file = new File("data.txt");
FileWriter fw = new FileWriter(file);
for (int[] row : sparseArr) {
for (int i : row) {
fw.write(i + "\t");
}
fw.write("\r\n");
}
fw.close();
// 3. 恢复原始数组
// 3.1 从磁盘文件中读取稀疏数组
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
// 记录读取的单行字符串
String line;
// 记录读取的当前的行数
int row = 0;
while((line = br.readLine()) != null) {
row++;
}
br.close();
// 3.2 创建稀疏数组
BufferedReader br1 = new BufferedReader(new FileReader("data.txt"));
int[][] sparseArr1 = new int[row][3];
row = 0;
while((line = br1.readLine()) != null) {
String[] temp = line.split("\t");
for(int i = 0; i < temp.length; i++) {
sparseArr1[row][i] = Integer.parseInt(temp[i]);
}
row++;
}
br1.close();
System.out.println("从磁盘读进来的稀疏数组:");
travarseArrayPrint(sparseArr1);
// 3.3创建原始数组并根据从磁盘读取的稀疏数组恢复原始数组
int[][] chessArr2 = new int[sparseArr1[0][0]][sparseArr1[0][1]];
for (int i = 1; i < sparseArr1.length; i++) {
for (int j = 0; j < sparseArr1[0].length; j++) {
chessArr2[sparseArr1[i][0]][sparseArr1[i][1]] = sparseArr1[i][2];
}
}
// 3.4 遍历输出恢复之后的原始数组
System.out.println("恢复之后的原始数组:");
travarseArrayPrint(chessArr2);
}
private static void travarseArrayPrint(int[] ...array) {
for (int[] row : array) {
for (int i : row) {
System.out.printf("%d\t", i);
}
System.out.println();
}
}
}