import java.io.*;
public class Demo01 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//创建一个原始的二维数组11*11
//0:表示没有棋子,1表示黑子 2代表白子
int chessArr1[][] = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
//创建原始二维数组棋盘
for (int[] row : chessArr1){
for (int data: row){
System.out.printf("%d\t",data);
}
System.out.println();
}
//将二维数组转稀疏数组的思路
//1.先遍历二维数组得到非0的数据个数
int sum = 0;
for(int i = 0 ; i< 11 ; i++){
for (int j = 0 ; j<11;j++){
if(chessArr1[i][j] !=0){
sum++;
}
}
}
//创建对应的稀疏数组
int[][] SpareArray = new int[sum + 1][3];
SpareArray[0][0] = 11; //存储的是原始数组的行数
SpareArray[0][1] = 11; //存储的是原始数组的列数
SpareArray[0][2] = sum; //存储的是原始数组的有限个数
//遍历二维数组拿到
int count = 0;
for(int i = 0 ; i< 11 ; i++){
for (int j = 0 ; j<11;j++){
if(chessArr1[i][j] !=0){
count++;
SpareArray[count][0] = i;
SpareArray[count][1] = j;
SpareArray[count][2] = chessArr1[i][j];
}
}
}
for(int i = 0;i<SpareArray.length;i++){
System.out.printf("%d\t%d\t%d\t\n",SpareArray[i][0],SpareArray[i][1],SpareArray[i][2]);
}
//恢复原始数组
int[][] chessArr2 = new int[SpareArray[0][0]][SpareArray[0][1]];
//获取稀疏数组中的值,添加到棋盘数组中
for(int i = 1;i < SpareArray.length;i++){ //已知稀疏数组的列,只需要遍历行来解决问题
int low = SpareArray[i][0] ;//一列存储的是棋盘行
int col = SpareArray[i][1] ;//第二列存储的是棋盘列
int val = SpareArray[i][2];//第三行存储的是棋子。
chessArr2[low][col] = val;
}
//创建文件,等待对象被序列化
File file = new File("feiyu.com.SpareArray//map.data");
boolean newFile = file.createNewFile();
System.out.println(newFile);
//序列化数组带创建的文件中
FileOutputStream fos = new FileOutputStream("feiyu.com.SpareArray//map.data");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(chessArr2);
fos.close();
oos.close();
//反序列化
FileInputStream fis = new FileInputStream("feiyu.com.SpareArray//map.data");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject();
int[][] a = (int[][]) o;
for (int[] ints : a) {
for (int anInt : ints) {
System.out.printf("%d\t",anInt);
}
System.out.println();
}
}
}
二维数组与稀疏数组的相互转换 和序列化 存储和反序列化读取
最新推荐文章于 2023-05-03 13:44:37 发布