当我们想要存储一个多维数组,且这个多为数组一样的元素很多(超过90%)我们就可以采用稀疏数组对其进行存储;
实现过程:首先我们自己构建一个二位数组,然后们把二维数组转为稀疏数组,再把稀疏数组进行还原操作;
在我们的代码中我们有一个将稀疏数组储存到文件中的一个过程;
import java.io.*;
/**
* @author: zfq
* @date: 2021/8/4 15:34
* @description:
*/
public class SparesArray {
public static void main(String[] args) throws IOException, ClassNotFoundException {
int[][] chess = new int[11][11];
chess[1][2] = 1;
chess[2][3] = 2;
chess[2][4] = 2;
System.out.println("原始数组==================");
for (int[] rows : chess) {
for (int data : rows) {
System.out.print("\t" + data);
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess.length; j++) {
if (chess[i][j] != 0) {
sum++;
}
}
}
int[][] sparesChess = new int[sum + 1][3];
sparesChess[0][0] = chess.length;
sparesChess[0][1] = chess.length;
sparesChess[0][2] = sum;
int count = 0;
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess.length; j++) {
if (chess[i][j] != 0) {
count++;
sparesChess[count][0] = i;
sparesChess[count][1] = j;
sparesChess[count][2] = chess[i][j];
}
}
}
System.out.println("稀疏数组====================");
for (int[] rows : sparesChess) {
for (int data : rows) {
System.out.print("\t" + data);
}
System.out.println();
}
System.out.println("写入文件ing。。。");
FileOutputStream out = new FileOutputStream("./data.data");
ObjectOutputStream stream = new ObjectOutputStream(out);
stream.writeObject(sparesChess);
out.close();
stream.close();
FileInputStream input = new FileInputStream("./data.data");
ObjectInputStream inputStream = new ObjectInputStream(input);
int[][] o = (int[][]) inputStream.readObject();
System.out.println("start读到文件。。。");
for (int[] rows : o) {
for (int data : rows) {
System.out.print("\t"+data);
}
System.out.println();
}
System.out.println("end读到文件。。。");
int[][] chessNew = new int[sparesChess[0][0]][sparesChess[0][1]];
for (int i = 1; i < sparesChess.length; i++) {
chessNew[sparesChess[i][0]][sparesChess[i][1]] = sparesChess[i][2];
}
System.out.println("恢复原始数据=================");
for (int[] rows : chessNew) {
for (int data : rows) {
System.out.print("\t" + data);
}
System.out.println();
}
}
}
运行代码截图如下: