Collection算是最顶级的一个接口,其中定义了一些集合很共性的方法,如size(),isEmpty(),add(),remove()等等,能够说是集合的规范数组
1、List(list最多见的的实现类有 ArrayList、linkedList、Queue等)ide
一、ArrayListthis
ArrayList是List接口的具体实现类,重写一下arrayList的主要方法:spa
public class MyList extends List {
//整个集合中最关键的部分,得有一个数组来存放数据
private Object[] elementData;
//数组得有长度,保存几个数据长度就为几
private Integer size;
public MyList(){
//初始化为10
this.elementData = new Object[10];
this.size = 0;
}
//添加方法,在List接口中 add方法的返回类型是boolean
public boolean add (Object obj){
/**
* 若是要添加的数据已经超过了数字的大小,则从新建立更大的数组
*
* 而且将原来的数组复制到新建立的数组中
*/
if(size >=elementData.length){
/**
* 底层的写法是这样,
* elementData.length << 1 至关于 elementData.length * 2
*/
// Object[] temp = new Object[elementData.length + (elementData.length << 1) ];
/**
* 建立一个容量更大到数组
*/
Object[] temp = new Object[elementData.length *2 ];
/**
* 将原来数组中的数据复制到新建的数组中
*
* System.arraycopy()方法所须要的参数注解:
*
* src the source array. 源数组(要复制的数组)
*
* srcPos starting position in the source array. 源数组中开始复制的位置
*
* dest the destination array. 目标数组 (新建的数组)
*
* destPos starting position in the destination data. 将源数组中的数据复制到新数组的哪一个位置
*
* length the number of array elements to be copied.要复制的源数组元素的数目
*/
System.arraycopy(elementData,0,temp,0,size);
elementData = temp;
}
//保存数据
elementData[size++] = obj;
return true;
}
@Override
public String toString() {
String value = "";
for (int i =0; i<elementData.length;i++){
if(elementData[i]!=null){
if(value.equals("")){
value=String.valueOf(elementData[i]);
}else {
value+=","+elementData[i];
}
}
}
return "["+value+"]";
}
}
因为ArrayList的特性,因此ArrayList添加比较慢,查找、遍历比较快3d
二、linkedListblog
最主要的就是其中add方法的理解,以下图接口