构造一个自己的ArrayList

package utils;

import java.util.ArrayList;

public class ArrayLists {

private int size=2;
private Object[] objData ;
int pos;


public ArrayLists() {
    this.objData = new Object[size];
}

//添加
public boolean add(Object obj) {
    Object[] obj1;
    
    
    if(pos==size)
    {
        size=size*2+1;
        obj1 = new Object[size];
        System.arraycopy(this.objData, 0, obj1, 0, this.objData.length);
        this.objData = obj1;
    }
    
    
    
    this.objData[pos]=obj;
    
    
    pos++;

    return true;
}

//获得
public Object get(int index) {
    if(index<0)
        try {
            throw new Exception("索引不能小于0");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    
    return this.objData[index]; 
}


//第一次出现
public int indexOf(Object obj)
{
    for(int i =0; i < this.objData.length ;i++)
    {
        if(objData[i]==obj)
        {
            return i;
        }
    }
    return -1;
}

//最后一次出现
public int lastIndexOf(Object obj)
{
    int posIndex=-1 ;
    for(int i = this.objData.length-1; i>=0 ;i--)
    {
        if(objData[i]==obj)
        {
        
            posIndex=i;
            break;
        }
    }
    return posIndex;
}

//清除
public void clear() {
    this.objData = new Object [this.objData.length];
}

//替换
public Object  set(int index,Object o)
{
    Object o1 = this.objData[index];
    this.objData[index]=o;
    return o1;
}



//移除
public Object  remove(int index) {
    
    Object indexOne ;
    Object[] pre;

    if(index<0) {
        try {
            throw new Exception("索引不能小于0");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    indexOne = this.objData[index];
    
    pre= new Object[this.objData.length-1];
    
    
    
    
    for(int i = 0, j = 0 ; i 

}

你可能感兴趣的:(构造一个自己的ArrayList)