仿照java用数组实现ArrayList
/*******************************************************************************
* JavaScript实现的ArrayList.
*
* @author Naga{jiangdragon@126.com}
* @version 2012/06/06
*
******************************************************************************/
function ArrayList() {
var args = ArrayList.arguments;
var initCapacity = 10;
if (args != null && args.length > 0)
initCapacity = args[0];
var elementData = new Array(initCapacity);
var size = 0;
this.size = function() {
return size;
};
this.isEmpty = function() {
return size == 0;
};
this.contians = function() {
return this.indexOf(obj) >= 0;
};
this.indexOf = function(obj) {
if (obj == null) {
for ( var i = 0; i < size; i++)
if (elementData[i] == null)
return i;
} else {
for ( var i = 0; i < size; i++)
if (elementData[i] == obj)
return i;
}
return -1;
};
this.lastIndexOf = function(obj) {
if (obj == null) {
for ( var i = size - 1; i >= 0; i--)
if (elementData[i] == null)
return i;
} else {
for ( var i = size - 1; i >= 0; i--)
if (elementData[i] == obj)
return i;
}
return -1;
};
this.get = function(index) {
rangeCheck(index);
return this.elementData[index];
};
this.setElementAt = function(index, obj) {
rangeCheck(index);
var oldValue = elementData[index];
this.elementData[index] = obj;
return oldValue;
};
this.add = function(obj) {
ensureCapacity(size + 1);
elementData[size++] = obj;
return true;
};
this.addElementAt = function(index, obj) {
if (index > size || index < 0) {
alert("ArrayIndexOutOfBoundsException," + index + ">=" + size);
return;
}
ensureCapacity(size + 1);
elementData[index] = element;
size++;
};
this.remove = function(index) {
rangeCheck(index);
var oldValue = elementData[index];
for ( var i = index; i < size - 1; i++) {
elementData[i] = elementData[i + 1];
}
elementData[--size] = null;
return oldValue;
};
this.clear = function() {
for ( var i = 0; i < size; i++)
elementData[i] = null;
size = 0;
};
this.toString = function() {
if (size == 0)
return "{}";
var str = "{";
for ( var i = 0; i < size; i++) {
str += elementData[i];
if (i == size - 1)
return str + "}";
str += ",";
}
};
function ensureCapacity(minCapacity) {
var oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
var oldData = elementData;
var newCapacity = parseInt((oldCapacity * 3) / 2 + 1);
if (newCapacity < minCapacity)
newCapacity = minCapacity;
elementData = new Array(newCapacity);
for ( var i = 0; i < oldCapacity; i++) {
elementData[i] = oldData[i];
}
}
};
function rangeCheck(index) {
if (index >= size) {
alert("ArrayIndexOutOfBoundsException," + index + ">=" + size);
return;
}
};
}