【发布时间】:2015-06-22 01:26:15
【问题描述】:
所以这个程序所做的就是使用 Iterator 方法处理 ArrayList 并打印出来。
我正在通过覆盖创建自己的迭代器,我需要帮助的是迭代器的删除方法。
代码:
public class MyArrayList implements Iterable<Object> {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;
private int currentSize;
int modCount = 0;
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public MyArrayList() {
size = 0;
capacity = DEFAULT_SIZE;
items = new Object[DEFAULT_SIZE];
this.currentSize = items.length;
}
@Override
public Iterator<Object> iterator() {
Iterator<Object> it = new Iterator<Object>() {
private int currentIndex = 0;
@Override
public boolean hasNext() {
try { return currentIndex <= currentSize && items[currentIndex] != null;
}catch(NoSuchElementException e){
System.out.println("There is nothing in the next element.");
}
return currentIndex <= currentSize && items[currentIndex] != null;
}
@Override
public Object next() {
checkForComodification();
try{
}catch(NoSuchElementException e){
System.out.println("There is nothing in the next element.");
}
return items[currentIndex++];
}
@Override
public void remove(){
if (lastRet< 0)
throw new IllegalStateException();
checkForComodification();
try {
MyArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
}catch (IndexOutOfBoundsException e){
throw new ConcurrentModificationException();
}
}
final void checkForComodification(){
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
};
return it;
}
private void expand() {
Object[] newItems = new Object[capacity + EXPANSION];
for (int j = 0; j < size; j++) newItems[j] = items[j];
items = newItems;
capacity = capacity + EXPANSION;
}
public void add(Object obj) {
try {
if (size >= capacity) this.expand();
items[size] = obj;
size++;
} catch (IndexOutOfBoundsException e) {
System.out.println("There is an error adding this word." + e.getMessage());
}
}
public int size() {
return size;
}
public Object get(int index) {
try {
return items[index];
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("ERROR- Cannot GET element. Index is out of range. Position: " +e.getMessage());
}
return items[index];
}
public boolean contains(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return true;
}
return false;
}
public void add(int index, Object obj) {
try {
if (size >= capacity) this.expand();
for (int j = size; j > index; j--) items[j] = items[j - 1];
items[index] = obj;
size++;
}catch (IndexOutOfBoundsException e){
System.out.println("ERROR- Cannot ADD element. Index out of range. Position: " +e.getMessage()+".");
}
}
public int indexOf(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return j;
}
return -1;
}
public boolean remove(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) {
for (int k = j; k < size - 1; k++) items[k] = items[k + 1];
items[size] = null;
size--;
return true;
}
}
return false;
}
public Object remove(int index) {
try {
Object result = this.get(index);
for (int k = index; k < size - 1; k++) items[k] = items[k + 1];
items[size] = null;
size--;
return result;
}catch(IndexOutOfBoundsException e){
System.out.print("ERROR- Cannot REMOVE element. Index out of range. Position: " + e.getMessage());
}
return null;
}
public void set(int index, Object obj) {
try {
items[index] = obj;
}catch (IndexOutOfBoundsException e){
System.out.println("ERROR- Cannot SET word.. Index out of range. Position: "+e.getMessage());
}
}
}
主要方法代码:
class Task4Test {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.size() + " animals: ");
for (int j = 0; j < zoo.size(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
String[] zooList = {"Cheetah", "Jaguar", "Leopard", "Lion", "Panther", "Tiger"};
for (String x: zooList) zoo.add(x);
printZoo();
System.out.printf("\nTesting the iterator\n>> ");
Iterator it = zoo.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.printf("\nTesting the iterator again without resetting\n>> ");
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.printf("\nTesting the iterator again after resetting\n>> ");
it = zoo.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.printf("\nTesting for-each loop\n>> ");
for(Object animal: zoo) System.out.print(animal + " ");
System.out.println();
System.out.println("\nLetting all the animals escape");
while (zoo.size()>0) zoo.remove(0);
printZoo();
System.out.printf("\nTesting the iterator with an empty list\n>> ");
it = zoo.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.println("\nTest complete");
}
}
现在打印出来: 动物园现在拥有 6 种动物:猎豹 Jaguar Leopard Lion Panther Tiger
Testing the iterator
>> Cheetah Jaguar Leopard Lion Panther Tiger
Testing the iterator again without resetting
>> //Is it supposed to be empty like this? (read below)
Testing the iterator again after resetting
>> Cheetah Jaguar Leopard Lion Panther Tiger
Testing for-each loop
>> Cheetah Jaguar Leopard Lion Panther Tiger
Letting all the animals escape
The zoo now holds 0 animals:
Testing the iterator with an empty list
>> Tiger //This is the main problem i'm trying to fix.
所以出于某种原因,Tiger 总是不断被打印出来。即使我改变了很多不同的方法。我感觉这可能与 Object remove(int index) 方法有关。
此外,我明白在“不重置的迭代器”部分之后应该什么都没有,但我的代码不应该有一个异常说“下一个元素中没有任何东西”?
【问题讨论】:
-
不太确定您的问题是什么。您不希望始终打印 Tiger 吗?如果是,那么您什么时候需要打印?
-
你能解释一下你的代码应该做什么,而不是简单地把它扔在这里让我们费力地通过吗?
-
@Cristik 抱歉,我的描述不够清楚。所以删除迭代器方法应该删除数组中的所有元素。所以应该没有打印任何东西,但它会打印出“Tiger”。
-
@HovercraftFullOfEels 对不起,我现在说得更清楚了。
-
为什么要创建自己的迭代器?为什么不使用集合自己的迭代器来删除项目?
标签: java iterator overriding iterable