您的位置:首页 > 理论基础 > 数据结构算法

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

2016-07-02 16:13 465 查看
将 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的区别

http://www.cnblogs.com/zhxhdean/archive/2011/03/25/1995431.html

//原函数
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: