重写List

重写List

多多分享

public class ListOfMy{
private Object[] obj;
private int num=0;

public ListOfMy(){
    obj=new Object[0];
}
 
public int size(){
    return num;
}
public boolean isEmpty() {
    if(obj==null || obj.length<1){
        return true;
    }
    return false;
}
 
public boolean contains(Object element) {
    for(int i=0; i<obj.length; i++){
        if(obj[i].equals(element)){
            return true;
        }
    }
    return false;
}
 
public boolean add(Object element) {
    if(element!=null){
        num++;
        obj=Arrays.copyOf(obj, num);
        obj[num-1]=element;
        return true;
    }
    return false;
}
public boolean remove(Object element){
    boolean f=false;
    for(int i=0,j=0; i<obj.length; i++){
        if(!obj[i].equals(element)){
            obj[j++]=obj[i];
            f=true;
        }
    }
    if(f){
        obj=Arrays.copyOf(obj, --num);
    }
    return f;
}
 
public void clear() {
    obj=new Object[0];
    num=0;
}
 
public Object get(int index)throws Exception{
    if(index<0 || index>num){
        throw new Exception("index无效");
    }
    return obj[index];
}
 
public int set(int index, Object element)throws Exception{
    if(index<0 || index>num){
        throw new Exception("index无效");
    }
    obj[index]=element;
    return index;
}
 
public void insert(int index, Object element)throws Exception{
    if(index<0 || index>num){
        throw new Exception("index无效");
    }
    num++;
    obj=Arrays.copyOf(obj, num);
    for(int i=0; i<index; i++){
        obj[i]=obj[i];
    }
    for(int i=num-1; i>index; i--){
        obj[i]=obj[i-1];
    }
    obj[index]=element;
}
 
public Object remove(int index)throws Exception{
    if(index<0 || index>num){
        throw new Exception("index无效");
    }
    Object ob=null;
    for(int i=0, j=0;i<num;i++){
        if(i!=index){
            obj[j]=obj[i];
            j++;
        }else{
            ob=obj[i];
        }
    }
    if(null!=ob){
        obj=Arrays.copyOf(obj, --num);
    }
    return ob;
}
 
public int indexOf(Object element) {
    for(int i=0; i<obj.length; i++){
        if(obj[i].equals(element)){
            return i;
        }
    }
    return -1;
}
public String toString(){
    StringBuilder sb=new StringBuilder("[");
    for(int i=0; i<num; i++){
        if(i>0)sb.append(",");
        sb.append(obj[i]);
    }
    sb.append("]");
    return sb.toString();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值