Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What collection to use instead of 2D array in Java?

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.

like image 574
Yatendra Avatar asked Jan 12 '10 16:01

Yatendra


2 Answers

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.

like image 159
helios Avatar answered Oct 21 '22 09:10

helios


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.

like image 39
Powerlord Avatar answered Oct 21 '22 10:10

Powerlord