其他分享
首页 > 其他分享> > 模仿ArrayList自定义容器对象MyArrayList

模仿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 +
            '}';
}

}
`

标签:count,index,自定义,int,ArrayList,Object,objects,MyArrayList,public
来源: https://www.cnblogs.com/sharkzzz/p/15774755.html