# Java二维数组转稀疏数组（文件保存与读取）

import java.io.*;

public class TestDemo {
public static void main(String[] args) {
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
//将二维数组转化成稀疏数组
//1.遍历二维数组，找到有效的数据个数sum
int sum = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[i].length; j++) {
if (chessArr1[i][j] != 0) {
sum++;
}
}
}
//2.遍历二维数组，给稀疏数组赋值
int[][] sparseArr = new int[sum + 1][3];
sparseArr[0][0] = chessArr1.length;
sparseArr[0][1] = chessArr1[0].length;
sparseArr[0][2] = sum;
int count = 1;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[i].length; j++) {
if (chessArr1[i][j] != 0) {
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
count++;
}
}
}
//3.遍历稀疏数组
for (int i = 0; i < sparseArr.length; i++) {
for (int j = 0; j < sparseArr[0].length; j++) {
System.out.print(sparseArr[i][j] + "\t");
}
System.out.println();
}
//4.将稀疏数组保存到map.txt中
saveArray("e:\\map.txt", sparseArr);
//5.从文件读取稀疏数组创建数组
//6.遍历二维数组
for (int i = 0; i < chessArr2.length; i++) {
for (int j = 0; j < chessArr2[i].length - 1; j++) {
System.out.print(chessArr2[i][j] + "\t");
}
System.out.println();
}
}

public static void saveArray(String filePath, int[][] array) {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(filePath));
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if (j == array[0].length - 1) {
bufferedWriter.write(array[i][j] + "");
} else {
bufferedWriter.write(array[i][j] + ",");
}
}
bufferedWriter.newLine();
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

public static int[][] readArray(String filePath) {
int[][] destArray = new int[0][];
try {
String line;
String[] split;
destArray = null;
int countLine = 0;
countLine++;
split = line.split(",");
if (countLine == 1) {
destArray = new int[Integer.parseInt(split[0])][Integer.parseInt(split[1])];
countLine++;
} else {
destArray[Integer.parseInt(split[0])][Integer.parseInt(split[1])] = Integer.parseInt(split[2]);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return destArray;
}
}

• 9
点赞
• 6
收藏
觉得还不错? 一键收藏
• 0
评论
06-03 550
03-07 332
01-24 285
08-29 354
08-11 255
01-02 374
10-27 417
08-06 424
08-06 940
08-08 249

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。