Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 244
Paulo Coghi Avatar asked Mar 30 '10 01:03

Paulo Coghi


People also ask

How are arrays and ArrayList similar?

Array and ArrayList both are used for storing elements. Array and ArrayList both can store null values. They can have duplicate values. They do not preserve the order of elements.

Are there 2D Arraylists?

Arrays can be created in 1D or 2D. 1D arrays are just one row of values, while 2D arrays contain a grid of values that has several rows/columns. 1D: 2D: An ArrayList is just like a 1D Array except it's length is unbounded and you can add as many elements as you need.

What is the difference between array and ArrayList Java?

Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed. We cannot store primitives in ArrayList, it can only store objects. But array can contain both primitives and objects in Java.

Whose performance is better array or ArrayList?

An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.


1 Answers

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

like image 86
Hardcoded Avatar answered Oct 18 '22 16:10

Hardcoded