ArrayList集合详解

 

基本使用语法:List(接口) a= new  ArrayList()(实现List接口的类,线程不安全),API中的E类型,表示泛型。

ArrayList也可以叫做动态数组,其常用的常用的5个方法基础代码实现:

a.add(“aaaaaaaaaaaa”)/给集合添加元素

其中Object [] o=new Object[10];int count=0;

public boolean add(Object e) {
if(count>=o.length){
//长度不够,,创建新数组,,长度为原来的1.5倍
Object [] item=new Object[(int)(o.length*1.5)];
//把旧数组的内容保存到新数组
for(int i=0;i<count;i++){
item[i]=o[i];
}
o=item;//用新数组覆盖原有数组

}
o[count]=e;
count++;
return true;
}

a.get(0)/获得集合中的第一个元素

public Object get(int index) {
return o[index];
}

a.size()/获得集合的长度

public int size() {
return count;
}

a.clear()/清空集合中的元素

public void clear() {
o=new Object[10];
count=0;
}

 

A.add(i,“插入的元素”)/从第i个元素处插入;

public void add(int index, Object element) {
if(count>=o.length){
//长度不够,,创建新数组,,长度为原来的1.5倍
Object [] item=new Object[(int)(o.length*1.5)];
//把旧数组的内容保存到新数组
for(int i=0;i<count;i++){
item[i]=o[i];
}
//新数组覆盖旧返数组
o=item;
}
for(int i=count;i>index;i--){
o[i]=o[i-1];
}
o[index]=element;
count++;
}

a.subList(第一个位置,第二个位置)/截取数组,原则带前不带后。

public List subList(int fromIndex, int toIndex) {
List list=new MyArrayList();
for(int i=fromIndex;i<toIndex;i++){
list.add(o[i]);
}
return list;
}

posted @ 2016-06-23 17:22  日光!  阅读(166)  评论(0)    收藏  举报