模仿ArrayList自定义容器对象MyArrayList

`public class MyArrayList{

private Object[] objects = new Object[10];

private int count;

public void add(Object value){
    if(count==objects.length){
        Object[] newObjects = new Object[count+1];
        System.arraycopy(objects,0,newObjects,0,objects.length);
        objects = newObjects;
    }
    objects[count++]=value;
}

public void add(int index,Object value){
    if(count==objects.length){
        Object[] newObjects = new Object[count+1];
        System.arraycopy(objects,0,newObjects,0,index);
        System.arraycopy(objects,index,newObjects,index+1,objects.length-index);
        objects = newObjects;
    }
    objects[count++]=value;
}

public void remove(int index){
    for (int i = 0; i < objects.length; i++) {
        if(objects[i] != null && objects[i] == objects[index]){
            System.arraycopy(objects,0,objects,0,i);
            System.arraycopy(objects,i+1,objects,i,objects.length-(i+1));
        }
    }
    count--;
}

public void remove(Object value){
    for (int i = 0; i < objects.length; i++) {
        if(objects[i] != null && objects[i] == value){
            System.arraycopy(objects,0,objects,0,i);
            System.arraycopy(objects,i+1,objects,i,objects.length-(i+1));
        }
    }
    count--;
}

public void set(int index,Object value){
    objects[index] = value;
}

public int size(){
    int num = 0;
    for (int i = 0; i < objects.length; i++) {
        if(objects[i] != null){
            num++;
        }
    }
    return num;
}

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

public boolean contains(Object value){
    for (int i = 0; i < objects.length; i++) {
        if(objects[i] != null && objects[i].equals(value)){
            return true;
        }
    }
    return false;
}

@Override
public String toString() {
    return "MyArrayList{" +
            "objects=" + Arrays.toString(objects) +
            ", count=" + count +
            '}';
}

}
`

上一篇:初学Django:第十二天,聚合函数,排序函数,关联查询,模型操作查询数据


下一篇:Mac上使用命令行安装brew,并通过brew安装Ant等工具