gpt4 book ai didi

java - Java 中的大矩阵

转载 作者:行者123 更新时间:2023-12-02 10:33:09 25 4
gpt4 key购买 nike

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

Java中有存储大矩阵的好方法吗?

我习惯了Python“导入库来为你做这件事”。 java中有合适的库吗?

This post不是我的问题的解决方案,因为在那篇文章中用户尝试存储字符串。解决方案是将字符串映射到整数,从而节省一些空间。我不能这样做。我只有一个大的整数矩阵。

最佳答案

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);
}
}

运行没有错误。

<小时/>

如果 martix 非常稀疏,则使用 Maps可以帮助。我建议使用这样的包装类。

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);
}
}

对于更全面的功能库,谷歌建议 https://java-matrix.org/其中对Java中的许多矩阵库进行了比较。

关于java - Java 中的大矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53490214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com