A dynamic array that can handle any kind of objects
/*
* This code is the dynamic object
*/
import android.util.Log;
public class DynamicArray {
private Object[] data;
public DynamicArray() {
data = new Object[1];
}
public Object get(int position) {
if (position >= data.length)
return 0;
else
return data[position];
}
public void put(int position, Object value) {
if (position >= data.length) {
int newSize = 2 * data.length;
if (position >= newSize)
newSize = 2 * position;
Object[] newData = new Object[newSize];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
Log.v("x", "Size of dynamic array increased to " + newSize);
}
data[position] = value;
}
}
/*
* The following code demonstrates the usage
*/
DynamicArray arr = new DynamicArray();
/* Add Integers and Strings */
arr.put(0, 123);
arr.put(1, "Hi There");
/* Output Array Content */
Log.v("Dynamic Array Test", "0: " + arr.get(0) + ", 1: " + arr.get(1));
2 Comments
hm. why not just use an ArrayList?
I'm with Berny -- use ArrayList.