Java 中的大型矩阵

Large matrixes in Java

我有一个大矩阵(大约 100x20.000.000)整数元素。我将其存储为列表的 ArrayList。不幸的是 Java 不喜欢这样,我收到了 OutOfMemoryError。

有没有什么好的方法可以在Java中存储一个大矩阵?

我习惯了蟒蛇"import library to do this for you"。 java 中是否有合适的库?

This post 不是我的问题的解决方案,因为 post 用户试图存储字符串。解决方案是将字符串映射为整数,从而节省一些 space。我不能这样做。我只有一个很大的整数矩阵。

I just have a big matrix of ints.

所以使用int

的大矩阵
int[][] ints = new int[100][500_000]; // uses about 200 MB each.

如果您有 List<List<Integer>> 个,每个将使用大约 8 倍。

我 运行 以下 -Xmx300m 是您正在使用的堆大小的 1/7。

public static void main(String... args) {
    int[][] ints = new int[100][500_000];
    for (int[] arr : ints) {
        Arrays.fill(arr, 1);
    }
}

这运行没有错误。


如果矩阵非常稀疏,使用 Maps 会有帮助。我建议使用这样的包装器 class。

import java.util.HashMap;
import java.util.Map;

public class SparseMatrix<T> {
    final Map<Integer, T>[] maps;
    final int rows, columns;

    public SparseMatrix(int rows, int columns) {
        maps = new Map[rows];
        for (int i = 0; i < rows; i++)
            maps[i] = new HashMap<>();
        this.rows = rows;
        this.columns = columns;
    }

    public int getRows() {
        return rows;
    }

    public int getColumns() {
        return columns;
    }

    public T get(int r, int c) {
        return maps[r].get(c);
    }

    public void set(int r, int c, T t) {
        maps[r].put(c, t);
    }
}

要获得更完整的功能库 google 建议使用 https://java-matrix.org/,其中对 Java 中的许多矩阵库进行了比较。