Skip to content

Commit

Permalink
迭代器
Browse files Browse the repository at this point in the history
  • Loading branch information
Ren650119726 committed Feb 23, 2017
1 parent e186438 commit 3fdaf66
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
38 changes: 35 additions & 3 deletions group17/102228177/src/data2_19/ArrayList.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package data2_19;

import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;


public class ArrayList implements List{
public static final int defLen = 10;
private Object[] elements;
Expand Down Expand Up @@ -97,9 +101,32 @@ public int size(){
return size;
}

// public Iterator iterator(){
// return null;
// }
public Iterator iterator(){
return new ArrayListIterator();
}

private class ArrayListIterator implements Iterator{
int cursor;

@Override
public boolean hasNext() {
return cursor != size;
}

@Override
public Object next() {
int i = cursor;
if(i >= size){
throw new NoSuchElementException();
}
if (i >= elements.length){
throw new ConcurrentModificationException();
}
cursor = i+1;
return elements[i];
}
}

public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(0);
Expand All @@ -112,5 +139,10 @@ public static void main(String[] args) {
for (int i = 0; i < list.size(); i++) {
System.out.println(i+":"+list.get(i));
}

Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
1 change: 1 addition & 0 deletions group17/102228177/src/data2_19/List.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package data2_19;

public interface List {

public void add(Object o);
public void add(int index, Object o);
public Object get(int index);
Expand Down

0 comments on commit 3fdaf66

Please sign in to comment.