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
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.
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.
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.
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.
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
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