# 二维数组转成稀疏数组，还原后存储到本地文件，并从文件读取还原出来的过程

二维数组转换为稀疏数组，并存储本地

package com.guo.sparseArrays;

import java.io.FileWriter;
import java.io.IOException;

public class SparseArrays {
public static void main(String[] args) throws IOException {
int count = 0;
int chessArray1[][] = new int[11][11];
chessArray1[1][2] = 1;
chessArray1[2][3] = 2;
chessArray1[4][5] = 2;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArray1[i][j] != 0) {
count++;
}
}
}
int sparse[][] = new int[count + 1][3];
sparse[0][0] = 11;
sparse[0][1] = 11;
sparse[0][2] = count;
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArray1[i][j] != 0) {
sum++;
sparse[sum][0] = i;
sparse[sum][1] = j;
sparse[sum][2] = chessArray1[i][j];
}
}
}
for (int i = 0; i < sparse.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", sparse[i][0], sparse[i][1], sparse[i][2]);
}
int newArray[][] = new int[sparse[0][0]][sparse[0][1]];
for (int i = 1; i < sparse.length; i++) {
newArray[sparse[i][0]][sparse[i][1]] = sparse[i][2];
}
FileWriter fw = new FileWriter("arrays.txt");
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
fw.write(newArray[i][j] + "\t");
}
fw.write("\n");
}
fw.close();
}
}


public class SparseArrays2 {
public static void main(String[] args) throws IOException {
List<String> stringList = new ArrayList<>();
String str;
}
int row = stringList.size();//查看文件有多少行
String s = stringList.get(0);
int columnNum = s.split("\\t").length;//查看数组哟多少列
int[][] newArrays = new int[row][columnNum];//创建对应行列数的二维数组
int count=0;//初始化行数
for ( String str2:stringList) {
String[] str3 = str2.split("\t");
for (int i=0;i<columnNum;i++) {
newArrays[count][i] = Integer.valueOf(str3[i]);
}

count++;
}
for (int i = 0; i <row ; i++) {
for (int j = 0; j < columnNum; j++) {
System.out.print(newArrays[i][j]+"\t");
}
System.out.print("\n");
}
}
}

08-27 158

11-24
08-06 2146
09-04 123
07-06 40