Java实现稀疏数组,可存储在硬盘,可恢复原数组
package com
.suanfa
;
import java
.io
.*
;
public class SpareseArray {
public static void main(String
[] args
) {
int sparese
[][] = ArrChangeSpr(InitArray());
PrinArray(sparese
);
SprToDisk(sparese
);
PrinArray(SprChangeArr(DiskTosqr()));
}
public static void PrinArray(int[][] arr
){
for (int[] arra
:
arr
) {
for (int value
:
arra
) {
System
.out
.print(value
+" ");
}
System
.out
.println();
}
}
public static int[][] InitArray() {
int array
[][] = new int[11][11];
array
[1][2] = 1;
array
[2][3] = 2;
return array
;
}
public static int[][] ArrChangeSpr(int[][] surceArray
) {
int sum
= 0;
int apareRow
= 1, col
= 0;
for (int[] row
:
surceArray
) {
for (int data
:
row
) {
if (data
!= 0) {
++sum
;
}
}
}
int spareArr
[][] = new int[sum
+ 1][3];
spareArr
[0][0] = 11;
spareArr
[0][1] = 11;
spareArr
[0][2] = sum
;
for (int i
= 0; i
!= surceArray
.length
; ++i
) {
for (int j
= 0; j
!= surceArray
[0].length
; ++j
) {
if (surceArray
[i
][j
] != 0) {
spareArr
[apareRow
][0] = i
;
spareArr
[apareRow
][1] = j
;
spareArr
[apareRow
++][2] = surceArray
[i
][j
];
}
}
}
return spareArr
;
}
public static int[][] SprChangeArr(int[][] array
) {
int cheseArr2
[][] = new int[array
[0][0]][array
[0][1]];
for (int i
= 1; i
!= array
.length
; ++i
) {
cheseArr2
[array
[i
][0]][array
[i
][1]] = array
[i
][2];
}
return cheseArr2
;
}
public static void SprToDisk(int[][] sqp
){
DataOutputStream out
=null
;
try {
out
=new DataOutputStream(new FileOutputStream("F:/test/test.dat"));
for (int[] arra
:
sqp
) {
for (int value
:
arra
) {
try {
out
.writeInt(value
);
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
} catch (FileNotFoundException e
) {
e
.printStackTrace();
}finally {
if (out
!=null
){
try {
out
.flush();
} catch (IOException e
) {
e
.printStackTrace();
}
try {
out
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
}
public static int[][] DiskTosqr(){
int sqr
[][]=new int[3][3];
DataInputStream fis
= null
;
try {
fis
= new DataInputStream(new FileInputStream("F:/test/test.dat"));
for (int i
=0;i
<sqr
.length
;++i
){
for (int j
=0;j
<sqr
[0].length
;++j
){
sqr
[i
][j
]=fis
.readInt();
}
}
} catch (FileNotFoundException e
) {
e
.printStackTrace();
} catch (IOException e
) {
e
.printStackTrace();
} finally {
if (fis
!=null
){
try {
fis
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
return sqr
;
}
}
转载请注明原文地址: https://lol.8miu.com/read-33826.html