I want to create a 100k x 100k matrix in java. The code is going to be execute in an online editor (Hack Reactor), so I can't increase heap size. I found somewhere that I can use SparseMatrix, but in this online editor I can't import the jars of SparseVector. So can you help to solve the problem? Should I use multi threading?
Asked
Active
Viewed 86 times
0
-
2100k x 100k of `int` objects is something like `40GB` worth of memory, why do you need this big of an array? – Mark Nov 30 '18 at 09:58
-
1How multithreading related to memory problem? – talex Nov 30 '18 at 09:59
-
1Try some of https://stackoverflow.com/questions/12626135/memory-efficient-sparse-array-in-java – Mark Jeronimus Nov 30 '18 at 09:59
-
@Mark I need to create this big array because it is part of a job test. – ana123 Nov 30 '18 at 10:01
-
You're not being consistent. If you need an array, then you can also not use SparseMatrix – Mark Jeronimus Nov 30 '18 at 12:45
1 Answers
0
You can use Map
as sparse matrix.
Just create class Pair
and use it as key.
class Pair {
final int x;
final int y;
Pair(int x, int y) {
this.x=x;
this.y=y;
}
public boolean equals(Object o) {
Pair other = (Pair)o;
return x==other.x&&y==other.y;
}
public int hashCode(){ return x ^ y; }
}
then declare
Map<Pair, Integer> matrix = new HashMap<>();
to set value use
matrix.put(new Pair(x, y), value);
to get value use
int value = matrix.get(new Pair(x, y));

talex
- 17,973
- 3
- 29
- 66