I want to use a collection in place of 2D array so that I don't need to give its size at the time of declaration and I can add as many elements as I want dynamically.
The problem with List> is you have to redimension each row if you want to redimension your matrix.
If you want to use a sparse matrix, or maybe an infinite matrix you can do something like:
class SparseMatrix<X> {
private Map<Coord, X> values = new HashMap<Coord, X>();
public SparseMatrix() {
}
public X get(int x, int y) {
return values.put(new Coord(x,y)); // null if there's no value
}
public void set(int x, int y, X value) { // you can use null (like in a List)
values.set(new Coord(x,y), value);
}
private static class Coord {
int x; int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (other instance of Coord) {
Coord o = (Coord) other;
return o.x == x && o.y == y;
}
return false;
}
@Override
public int hashCode() {
return o.x + o.y; // or some more clever implementation :)
}
}
}
Edit: Apache Commons HashCodeBuilder is a great tool for generating hash-codes.
The easiest way is to use nested collections... say (assuming your values are Strings) List<List<String>>
which can then be used like this:
List<List<String>> fakeArray = new ArrayList<List<String>>();
// Pretend you fill it with values between these calls
String retrieve = fakeArray.get(0).get(0);
Edit: This was originally a Map<String,List<String>>
which really doesn't make sense in this context.
However, you may want to see if Google Collections or Apache Commons Collections have something more specialized that you can use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With