开发者

Java: Bidimensional Array with methods/capabilities similar to ArrayList

I want to create an XY开发者_运维知识库 array of integers (or whatever type), but I want to use methods like "add", "remove", "contains", "indexOf" similar to ArrayList class.

Is there any existing class with these capabilities?

PS: I don't want to create an ArrayList of ArrayList


No, AFAIK there isn't any class like this. But Implementing one should be fairly easy:

class BiDimensionalArray<T>{
  Object[][] backupArray;
  int lengthX;
  int lengthY;

  public BiDimensionalArray(int lengthX, int lengthY) {
    backupArray = new Object[lengthX][lengthY];
    this.lengthX = lengthX;
    this.lengthY = lengthY;
  }

  public void set(int x, int y, T value){
    backupArray[x][y] = value;
  }

  public T get(int x, int y){
    return (T) backupArray[x][y];
  }

  public void addX(T[] valuesY) {
    Object[][] newArray = new Object[lengthX+1][lengthY];
    System.arraycopy(backupArray, 0, newArray, 0, lengthX);
    newArray[lengthX]=valuesY;
    backupArray = newArray;
    lengthX = lengthX+1;
  }
}

Note: The Typeparameter isn't used internally, because there is no such thing as new T[][]

EDITS
Added addX Method for demonstration
Fixed compile-errors


From your description, I would suggest you to try using JAMA.
You can also create your own implementation for an XY Matrix. However, for doing this, you will have to decide what exactly you want from the implementation.
If your Matrix is not of fixed size, then you can use something like the 3-tuple format for storing matrices. (This representation is efficient only if your matrix is sparse). Internally, you will use three ArrayLists; one for storing the row number, second for storing the column number and the third for storing the actual value.
Accordingly, you will write the add(int row, int column, int value) method, which takes care of things like keeping the ArrayLists sorted by row number, then by column number, etc. to increase the efficiency of random accesses.
With this representation, you can implement all the methods like remove(), contains(), that are available for ArrayList.


There are no native matrix types in the standard Java libraries. That being said, it's fairly easy to create one. The methods are trivial to implement and you can back it with an array, a List or whatever.

public class Matrix<T> {
  private final List<T> values;
  private final int rows;

  public Matrix(int x, int y) {
    this.rows = x;
    values = new ArrayList<T>(x * y);
  ]

  public int get(int x, int y) {
    return values.get(x * rows + y);
  }

  public boolean contains(T t) {
    return values.contains(t);
  }

  // etc
}


check out JAMA, it's from the Mathworks and NIST.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜