A matrix is usually implemented by an actual 2D array: T. However, this requires, for an M by N matrix, M*N references to T. If many of those are null, you waste a lot of space.
You can instead use a linked list of sorts, where each node has a reference to the next non-null cell (or non-0 / non-false for primitives). Implementing this was an exercise in my 2nd year of University.
Seeing as that is 9 years ago, I can't remember any of the details though...
One easy way to do it is to use a Map. Let the keys be Strings that look like "M,N" where M and N are the array indices. That way if you have a 100x100 array with 5 elements in it, you've got just a Map with the five key/value pairs stored. Write get/set methods like
I'd use a Map<Point,T> instead. That makes it easier to parse back if needed, and it is most likely more efficient than a string too. String has a char and three ints as fields, whereas Point only has two ints.
Of course Point does have the drawback of being highly mutable, but as long as you don't publicize the Point objects that's not a problem.
One of the things not mentioned in the original requirements description was whether you want to find all the entries in a row of the array. Or whether you want to find all the entries in a column. That would influence whether you used a bunch of linked lists, or a map, or something else.
You create your own Point classThis is an immutable class, and final (so you can safely use instanceof in the equals method) and works out its hash code early (because you intend to use it in structures which use hash codes frequently). The hash code is worked out on the assumption that you will be using values between 0 and 100, and the % operators are so as to get more variability in the low-order part of the hash code. It is probably full of spelling errrors, but you will find them out when you get the compiler errors.
[pedantic mode]By the way, there is no such thing as a two-dimensional array in Java, only an array of arrays.[/pedantic mode]