您好,欢迎来到微智科技网。
搜索
您的当前位置:首页复习(数据结构:java):线性表(数组):泛型的写法

复习(数据结构: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;
}

  • “==”和 equals的区别
//原函数
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;
        }
    }

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 7swz.com 版权所有 赣ICP备2024042798号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务