package com.test01;
import java.io.*;
/**
*稀疏数组的应用
*/
public class Run {
private static String path ="D:\\data.dat";
public static void main(String[] args) throws IOException, ClassNotFoundException {
//初始化一个二维数组
int [][] arr = new int[11][11];
arr[1][2]= 1;
arr[2][3] = 2;
//遍历数组
System.out.println("\n初始数组(arr)的遍历");
traverseArr(arr);
//得到arr的稀疏数组
int [][]sparse = getSparseArr(arr);
//遍历稀疏数组
System.out.println("\n稀疏数组(sparse)的遍历");
traverseArr(sparse);
//还原稀疏数组
int [][]newArr = restoreArr(sparse);
//遍历还原后的数组
System.out.println("\n还原稀疏数组后的数组(newArr)");
traverseArr(newArr);
//IO流的应用
writeFile(sparse);
//使用IO流还原的原数组
int [][] newArr_ = restoreArr(readFile());
//遍历还原后的数组(newArr_)
System.out.println("\n使用IO流还原稀疏数组后的数组(newArr_)");
traverseArr(newArr_);
}
public static void traverseArr(int[][] arr){//遍历数组
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
}
public static int [][] getSparseArr(int [][] arr){//转为稀疏数组
int row = arr.length;//行
int list = arr[0].length;//列
int count = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < list; j++) {
if(arr[i][j]!=0){
count++;
}
}
}
int [][]sparseArr = new int[count+1][3];
sparseArr[0][0] = row;
sparseArr[0][1] = list;
sparseArr[0][2] = count;
int num = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < list; j++) {
if(arr[i][j]!=0){
num++;
sparseArr[num][0] = i;
sparseArr[num][1] = j;
sparseArr[num][2] = arr[i][j];
}
}
}
return sparseArr;
}
public static int [][] restoreArr(int [][]sparse){
int [][]arr = new int[sparse[0][0]][sparse[0][1]];
for (int i = 1; i < sparse[0][2] + 1; i++) {
arr[sparse[i][0]][sparse[i][1]] = sparse[i][2];
}
return arr;
}
public static void writeFile(int [][]arr) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
oos.writeObject(arr);
oos.close();
}
public static int [][] readFile() throws IOException, ClassNotFoundException {
File file = new File(path);
if(!file.exists()){
System.out.println("没有找到相关文件");
return null;
}
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
Object o = ois.readObject();
int [][]arr = (int [][]) o;
return arr;
}
}
java 稀疏数组(结合IO流)
最新推荐文章于 2025-12-08 16:37:50 发布
由于未提供博客具体内容,无法给出包含关键信息的摘要。
955

被折叠的 条评论
为什么被折叠?



