稀疏数组
什么是稀疏数组?
假设有这样的一个二维数组
shape是11x11,但是很多数据都是0,比较浪费空间,我们可以通过一些方法来压缩这个数组,稀疏数组就是一种压缩数组的方法,通过稀疏数组变换后,原数组变为
变成了4X3,节约了很多空间
稀疏数组存储原理
当一个数组中大部分元素为0,或者为同一个值的数组时,可以使用稀疏数组来保存该数组。
稀疏数组处理数据的方法是:
- 记录数组一共有几行几列,有多少个不同的值
- 把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模
稀疏数组的实现
1.定义一个SparseArray类
public class SparseArray implements Serializable {
private static int[][] array1;
public SparseArray(int[][] array1) {
this.array1 = array1;
}
public SparseArray() {
}
}
2.向SparseArray类中添加将普通数组变为SparseArray的方法
public void toself(int[][] sou){
int row = sou.length;
int col = 0;
int count = 0;
for (int[] so:sou){
col = so.length;
for (int s:so){
if (s!=0){
count++;
}
}
}
array1 = new int[count+1][3];
array1[0][0] = row;
array1[0][1] = col;
array1[0][2] = count;
int target = 1;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (sou[i][j]!=0){
array1[target][0] = i;
array1[target][1] = j;
array1[target][2] = sou[i][j];
target++;
}
}
}
}
3.向SparseArray中添加将稀疏数组变为普通数组的方法
public int[][] toarray(){
int[][] result = new int[array1[0][0]][array1[0][1]];
for (int[] demp:array1){
result[demp[0]][demp[1]] = demp[3];
}
return result;
}
4.为了方便测试,给SparseArray类添加print方法
public void print(){
System.out.println(array1[0][0]+"---"+array1[0][1]+"---"+array1[0][2]);
System.out.println("---------------------------------------");
for (int i = 1; i <= array1[0][2]; i++) {
System.out.println(array1[i][0]+"---"+array1[i][1]+"---"+array1[i][2]);
}
}
补充:将SparseArray类存入磁盘和磁盘中读取
1,存盘
public static void save(SparseArray obj,String path){
File file = new File(path);
OutputStream out;
try {
out = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
objectOutputStream.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2,读取
public static SparseArray read(String path){
File file = new File(path);
InputStream in;
try {
in = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(in);
Object o = objectInputStream.readObject();
SparseArray res = (SparseArray)o;
in.close();
return res;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}