开发者

Sorting Loop in Java

There is a list of objects I need to add to a grid without receiving an IndexOutOfBoundsException. Each object has two numbers associated with it which corresponds to it's index and column position in a grid. There can be 3 columns and unlimited rows. I need to call add() method for this grid but only in the correct order, so :

(0,0),(0,1),(0,2),(1,0)...

Th开发者_Python百科e grid would therefore look like this:

  0 1 2
0 x x x
1 x x x
2 x x x
3 x x x

I must also take into account the chance that no object exists for a certain position. For example:

A) x x x  B) x   x   C) x x x
   x x x     x   x        x x
   x   x         x        x
   x   x         x        x
   x   x

Can this be done? I'm not sure where to start.


Maybe you should think about another datastructure that stores objects by (row,column). It's interface would look like

public interface GridModel {
  void set(int row, int column, Object o);
  Object get(int row, int column)
}

And than you can use a list of lists to store the data. List<List<Object>> or, as Mark Peters suggests, a sparse matrix

If working with the cell values is important, add a cell iterator method. A simple implementation would look like:

public Iterable<Object> cellIterator() {
    final List<Object> items = new java.util.ArrayList<Object>();
    for(final List<Object> row : cells) {
        for(final Object cell: row) {
            items.add(cell);
        }
    }
    return items;
}


What you are looking for is probably a sparse matrix implementation.

One of the most simple implementations of this is the dictionary-of-keys approach, which is basically a table linking coordinates to an object. Something like this:

Map<Point, T> grid = new HashMap<Point, T>();
grid.put(new Point(5, 2), myObj);

Point would be a class you implement containing a column and index field, with hashCode() and equals() properly implemented. Or, if you're really lazy, you could hack it by using java.awt.Point.

You could encapsulate this within an interface similar to the one suggested by @sblundy. I'd suggest something like this:

public interface Grid<T> {
   public T set(int column, int index, T val);
   public T get(int column, int index);
   //other optional methods
}


The answer to this question may help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜