手写List方法源码
模拟手写list部分常用方法的源码,加深对list源码的理解,话不多说,直接上代码:
/**
* 模拟手写list源码
*/
public class TestList {
/**
* 集合容量
*/
private int size;
/**
* 元素个数
*/
private Object[] elementDate;
public TestList() throws Exception {
this(10);
}
public TestList(int initIndex) throws Exception {
if (initIndex <= 0){
throw new Exception("初始化索引不能小于1");
}
elementDate = new Object[initIndex];
}
/**
* 返回集合元素个数
* @return 元素个数
*/
public int size(){
return elementDate.length;
}
/**
* 往集合中添加元素
*/
public void add(Object obj) throws Exception {
//先进行容量检查,判断是否越界
checkListSize(size++);
elementDate[size++] = obj;
}
/**
* 往集合中添加元素
*/
public void add(int index,Object obj){
checkListSize(size++);
System.arraycopy(elementDate,index,elementDate,index+1,size-index);
elementDate[index] = obj;
size++;
}
/**
* 移除元素
* @param index 索引位置
* @throws Exception Exception
*/
public void remove(int index) throws Exception {
if (index < 0 || index > size+1){
throw new Exception("索引值不正确");
}
System.arraycopy(elementDate,index,elementDate,index-1,size-index-1);
size--;
}
/**
* 移除元素
* @param obj 元素
* @throws Exception Exception
*/
public void remove(Object obj) throws Exception {
for (int i = 0; i < elementDate.length; i++) {
if (obj.equals(elementDate[i])){
System.arraycopy(elementDate,i+1,elementDate,i,size-i-1);
size--;
}
}
}
/**
* 根据索引获取元素
* @param index 索引位置
* @return 目标元素
*/
public Object get(int index){
if (index < elementDate.length && index >= 0){
return elementDate[index];
}
return null;
}
/**
* 设置替换元素
* @param index 索引
* @param obj 元素
* @return 异常
*/
public boolean set(int index,Object obj){
if (index < elementDate.length && index >= 0){
elementDate[index] = obj;
return true;
}
return false;
}
/**
* 容量检查,判断是否需要扩容
* @param size 下标
*/
private void checkListSize(int size){
//如果元素个数大于容量,进行扩容
if (size > elementDate.length){
Object[] newList = new Object[size*2+1];
//老集合从0索引开始复制,新集合从0开始到老集合的长度
System.arraycopy(elementDate,0,newList,0,elementDate.length);
/*for (int n = 0; n < newList.length; n++) {
newList[n] = elementDate[n];
}*/
}
}
public static void main(String[] args) throws Exception {
TestList list = new TestList();
list.add(123);
list.add("456");
list.add(0,789);
list.add(1,"7894");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println();
list.remove("7894");
list.set(0,7788);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}