复习(数据结构:java):线性表(数组):泛型的写法

  • ArrayIntList 转换为 ArrayList<E>

//原始函数
public ArrayIntList(int capacity){
    if(capacity < 0)
        throw new IllegalArgumentException("cpapcity: "+capacity);
    elementData = new int[capacity];
    size=0;
}
//直接泛化,会错误
// 不可以创建泛型的数组
//可以创建Object[]数组

public ArrayIntList(E capacity){
    if(capacity < 0)
        throw new IllegalArgumentException("cpapcity: "+capacity);
    elementData = new E[capacity];
    size=0;
}

//修改后的泛型;
//可以消除注释的方法
//@suppressWarining("unchecked")
public ArrayIntList(E capacity){
    if(capacity < 0)
        throw new IllegalArgumentException("cpapcity: "+capacity);
    elementData = (E())new object[capacity];
    size=0;
}

//原函数
public int indexof(E value){
    for(int i=0;i<size;i++){
        if(elementData[i]==value)
            return i;
    }

    return -1;
}

//修改

public int indexof(E value){
    for(int i=0;i<size;i++){
        if(elementData[i]。equals(value))
            return i;
    }

    return -1;
}

  • 内部类
  • 在类的内部声明一个类,内部的类的对象,可以访问外部类的方法和字段
  • ArryaListIterator<E>Iterator<E>
private class ArrayListIterator implements Iterator<E> {
        private int position;           // current position within the list
        private boolean removeOK;       // whether it's okay to remove now

        // post: constructs an iterator for the given list
        public ArrayListIterator() {
            position = 0;
            removeOK = false;
        }

        // post: returns true if there are more elements left, false otherwise
        public boolean hasNext() {
            return position < size();
        }

        // pre : hasNext() (throws NoSuchElementException if not)
        // post: returns the next element in the iteration
        public E next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            E result = elementData[position];
            position++;
            removeOK = true;
            return result;
        }

        // pre : next() has been called without a call on remove (throws
        //       IllegalStateException if not)
        // post: removes the last element returned by the iterator
        public void remove() {
            if (!removeOK) {
                throw new IllegalStateException();
            }
            ArrayList.this.remove(position - 1);
            position--;
            removeOK = false;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值