js实现ArrayList功能附实例代码
1.ArrayList方法摘要
构造方法摘要
ArrayList()
构造一个初始容量为10的空列表。
ArrayList(Collection<?extendsE>c)
构造一个包含指定collection的元素的列表,这些元素是按照该collection的迭代器返回它们的顺序排列的。
ArrayList(intinitialCapacity)
构造一个具有指定初始容量的空列表。
方法摘要
booleanadd(Ee)
将指定的元素添加到此列表的尾部。
voidadd(intindex,Eelement)
将指定的元素插入此列表中的指定位置。
booleanaddAll(Collection<?extendsE>c)
按照指定collection的迭代器所返回的元素顺序,将该collection中的所有元素添加到此列表的尾部。
booleanaddAll(intindex,Collection<?extendsE>c)
从指定的位置开始,将指定collection中的所有元素插入到此列表中。
voidclear()
移除此列表中的所有元素。
Objectclone()
返回此ArrayList实例的浅表副本。
booleancontains(Objecto)
如果此列表中包含指定的元素,则返回true。
voidensureCapacity(intminCapacity)
如有必要,增加此ArrayList实例的容量,以确保它至少能够容纳最小容量参数所指定的元素数。
Eget(intindex)
返回此列表中指定位置上的元素。
intindexOf(Objecto)
返回此列表中首次出现的指定元素的索引,或如果此列表不包含元素,则返回-1。
booleanisEmpty()
如果此列表中没有元素,则返回true
intlastIndexOf(Objecto)
返回此列表中最后一次出现的指定元素的索引,或如果此列表不包含索引,则返回-1。
Eremove(intindex)
移除此列表中指定位置上的元素。
booleanremove(Objecto)
移除此列表中首次出现的指定元素(如果存在)。
protectedvoidremoveRange(intfromIndex,inttoIndex)
移除列表中索引在fromIndex(包括)和toIndex(不包括)之间的所有元素。
Eset(intindex,Eelement)
用指定的元素替代此列表中指定位置上的元素。
intsize()
返回此列表中的元素数。
Object[]toArray()
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组。
<T>T[]toArray(T[]a)
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。
voidtrimToSize()
将此ArrayList实例的容量调整为列表的当前大小。
2.js实现部分功能
<html>
<scripttype="text/javascript"src="json.js"></script>
<head>
<scripttype="text/javascript">
functionArrayList(){
this.arr=[],
this.size=function(){
returnthis.arr.length;
},
this.add=function(){
if(arguments.length==1){
this.arr.push(arguments[0]);
}elseif(arguments.length>=2){
vardeleteItem=this.arr[arguments[0]];
this.arr.splice(arguments[0],1,arguments[1],deleteItem)
}
returnthis;
},
this.get=function(index){
returnthis.arr[index];
},
this.removeIndex=function(index){
this.arr.splice(index,1);
},
this.removeObj=function(obj){
this.removeIndex(this.indexOf(obj));
},
this.indexOf=function(obj){
for(vari=0;i<this.arr.length;i++){
if(this.arr[i]===obj){
returni;
};
}
return-1;
},
this.isEmpty=function(){
returnthis.arr.length==0;
},
this.clear=function(){
this.arr=[];
},
this.contains=function(obj){
returnthis.indexOf(obj)!=-1;
}
};
//新建一个List
varlist=newArrayList();
//增加一个元素
list.add("0").add("1").add("2").add("3");
//增加指定位置
list.add(2,"22222222222");
//删除指定元素
list.removeObj("3");
//删除指定位置元素
list.removeIndex(0);
for(vari=0;i<list.size();i++){
document.writeln(list.get(i));
}
document.writeln(list.contains("2"))
</script>
</head>
<body>
</body>
</html>