import java.io.*;
import java.util.Arrays;
public class Test01 {
public static void main(String[] args) {
//创建一个原始的二维数组11*11
//0表示没有棋子,1表示黑色,2表示蓝色
int[][] chessArrs = new int[11][11];
chessArrs[1][2] = 1;
chessArrs[2][3] = 2;
int sum = 0;
for (int i = 0; i < chessArrs.length; i++) {
for (int j = 0; j < chessArrs[i].length; j++) {
if (chessArrs[i][j] != 0) {
sum += 1; //获取原始二维数组中的非0元素个数
}
}
}
int[][] chess = new int[sum + 1][3]; //给稀疏数组的第一行赋值
chess[0][0] = chessArrs.length; //原始数组的行
chess[0][1] = chessArrs[0].length; //原始数组的列
chess[0][2] = sum; //元素数组的非0元素个数
//给稀疏数组剩下的部分赋值
int count = 0; //控制稀疏数组的行
for (int i = 0; i < chessArrs.length; i++) {
for (int j = 0; j < chessArrs[i].length; j++) {
if (chessArrs[i][j] != 0) {
count += 1;
chess[count][0] = i; //第count个原数组非零元素的行
chess[count][1] = j; //第count个原数组非零元素的列
chess[count][2] = chessArrs[i][j]; //第count个原数组非零元素的值
}
}
}
//根据稀疏数组复原原始数组
int[][] chessArr1 = new int[chess[0][0]][chess[0][1]];
for (int i = 1; i < chess.length; i++) {
chessArr1[chess[i][0]][chess[i][1]] = chess[i][2];
}
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[i].length; j++) {
// System.out.print(chessArr1[i][j] + "\t");
}
// System.out.println();
}
//把稀疏数组序列号
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("map.txt"));
oos.writeObject(chess);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//读稀疏数组
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("map.txt"));
int[][] chess1 = (int[][])ois.readObject();
System.out.println(Arrays.deepToString(chess1));
} catch (Exception e) {
e.printStackTrace();
}finally {
if (ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
09-08
815
03-21
424
09-13
2407